Just learning Classes in C++, I thought I had a fairly good grip on it but for some reason this code won’t even compile.
#include <iostream>
#include <cstdlib>
using namespace std;
class Position
{
int row;
int column;
public:
Position(); //constructor
~Position(); //destructor
void setPos(int, int); //set the position
int getRow(); //return the current row
int getColumn(); //return the current column
void getPos(); //print the pos
bool compare(int, int); //compare a row and column with the one in the class
};
Position::Position()
{}
Position::~Position()
{}
void Position::setPos(int x, int y)
{
Position.row = x;
Position.column = y;
}
int Position::getRow()
{
return Position.row;
}
int Position::getColumn()
{
return Position.column;
}
void Position::getPos()
{
cout << "Row: " << Position.row << "Column: " << Position.column;
}
bool Position::compare(int x, int y)
{
if(x == Position.row && y == Position.column)
return true;
else
return false;
}
Running this code straight in MS Visual Studio 2010 yields these compiling problems:
...prob2.cpp(30): error C2143: syntax error : missing ';' before '.'
Line 30 is: Position.row = x;
I don’t see why or where there should be a ; anywhere there.
I get this error on several other lines including the one right under it.
I should note that I don’t have a main function although I don’t think this is needed.
You don’t need to prefix instance variables using the class name, instead use
roworthis->rowEDIT:
Eventually you will want to move the class declaration to a header file ie.
position.hand keep the implementation in theposition.cppfile with#include "position.h"at the top. This will make your Position class usable in other files.