刚刚学习 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 函数,尽管我认为这不是必需的。
最佳答案
您不需要使用类名作为实例变量的前缀,而是使用 row
或 this->row
编辑:
最终您会希望将类声明移动到头文件中,即。 position.h
并将实现保留在 position.cpp
文件中,#include "position.h"
位于顶部。这将使您的 Position 类可用于其他文件。
关于C++ 这个简单的类有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7438834/