0

Hey everyone,

I'm having an issue with the simplest vector functions. I'm trying to add a Piece object to a vector, but it's data members are being changed when I do... am I missing something?

/* Piece.h */
#ifndef _PIECE_H
#define	_PIECE_H

class Piece {
public:
    Piece();
    Piece(int r, int c);
    Piece(const Piece& orig);
    virtual ~Piece();
    int r;
    int c;
private:

};

#endif	/* _PIECE_H */



#include <stdlib.h>
#include <vector>
#include <iostream>
#include "Piece.h"

using namespace std;

int main(int argc, char** argv) {
    Piece a(1,2);
    
    vector<Piece> vect;
    vect.push_back(a);
    cout << "Inside vector: " << vect[0].c << endl; //prints out 0 instead of 2
    cout << "Outside vector: " << a.c << endl; //prints out 2 like it should

    return (EXIT_SUCCESS);
}

/* Piece.cpp */
//#include "Piece.h"

Piece::Piece() {
   
}

Piece::Piece(int r, int c){
    this->r = r;
    this->c = c;
}
Piece::Piece(const Piece& orig) {
}

Piece::~Piece() {
}

Edited by tnclark8012: rearraged code

3
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by tnclark8012
0

Think about the order of your code. Think about what your program knows before it tries to use something.

If your program begins and it hasn't been told there is a class called "Piece", then how can it add that class to a vector?

Edited by HealBrains: n/a

0

Think about the order of your code. Think about what your program knows before it tries to use something.

If your program begins and it hasn't been told there is a class called "Piece", then how can it add that class to a vector?

Sorry, I should be more clear, I'll rearrange it. I'm using Netbeans, so the 3 files I posted are all separate files and are being compiled by Netbeans.

Edited by tnclark8012: n/a

0

The first thing that jumped out at me was the 'this->'. Why are you doing that? If you're instantiating a class and editing its member variables they should be intrinsic to that instance of the class anyways, so there's no reason to use 'this'.

Edited by HealBrains: n/a

0

Thank you! I don't know why I didn't realize it! lol Now on to the rest of my assignment... We're supposed to use the min-max algorithm to game a Gumoku (connect 5) game. I think if I keep the coordinates (indexes of a multi-dimensional array) of each players pieces in a vector I could be a little more efficient checking over the board

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.