C ++这个简单的类有什么问题?

时间:2011-09-16 00:04:59

标签: c++ class

刚学习C ++中的Classes,我认为我对它有相当好的把握,但由于某种原因,这段代码甚至都不会编译。

#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;
}

在MS Visual Studio 2010中直接运行此代码会产生以下编译问题:

...prob2.cpp(30): error C2143: syntax error : missing ';' before '.'
第30行是:Position.row = x; 我不明白为什么或哪里应该有;

我在其他几行上得到了这个错误,包括它下面的一行。

我应该注意到我没有主要功能,虽然我不认为这是必需的。

1 个答案:

答案 0 :(得分:5)

您不需要使用类名称为实例变量添加前缀,而是使用rowthis->row

编辑:

最终,您需要将类声明移动到头文件,即。 position.h并将实施保留在position.cpp文件中,#include "position.h"位于顶部。这将使您的Position类可用于其他文件。

相关问题