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

标签 c++ class

刚刚学习 C++ 中的类,我认为我已经很好地掌握了它,但出于某种原因,这段代码甚至无法编译。

#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):错误 C2143:语法错误:缺少“;”在“.”之前
第 30 行是:Position.row = x; 我不明白为什么或哪里应该有 ; 那里的任何地方。

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

我应该注意到我没有 main 函数,尽管我认为这不是必需的。

最佳答案

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

编辑:

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

关于C++ 这个简单的类有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438834/

相关文章:

c# - 从 C++ 启动 C# .Net 应用程序

c++ - ProtocolBuffer,SerializeToArray() 上的 abort()

c++ - 同类的类(class)成员?

c# - 在不同的类中使用某些变量 (C#)

c++ - 使用C在定点运算中使用32位数据进行64位操作

c++ - 如何使用模板生成常规参数列表并将其传递给运行时函数?

java - 在不知道类名的情况下调用构造函数(java)

javascript - 为什么我不能在调用 super 构造函数的箭头函数中使用 "this"?

c++ - 具有传递引用对象的类会产生编译错误

java - 卡在 NPE 将 Array.toString(object) 分配给类中的另一个数组上