带有Getter函数的C++中出错
Error in C++ with a Getter function
当我尝试显示一些信息时,遇到了一个奇怪的错误。这是我类代码的一部分:
class Vertex
{
public:
Vertex(int name)
{
name = name;
pred = NULL;
color = 'w';
desc = 1000000;
}
int getName() {return name;}
char getColor() {return color;}
Vertex* getPred() {return pred;}
int getDesc() {return desc;}
void setColor(char c) {color = c;}
void setPred(Vertex *p) {pred = p;}
void setDesc(int d) {desc = d;}
private:
int name;
char color;
Vertex* pred;
int desc;
};
我相信这没关系。。。但当我在我的主要功能中这样做时(我相信这也没关系…):
for(int z = 1; z <= nsomething; z++){
Vertex v(z);
cout << "from z=" << z << " is vertex name: " << v.getName() << endl;
cout << "from z=" << z << " is vertex color: " << v.getColor() << endl;
Vertex *vp = &v;
cout << "from z=" << z << " is vertex name: " << vp->getName() << endl;
cout << "from z=" << z << " is vertex color: " << vp->getColor() << endl;
}
我得到这个:
from z=1 is vertex name: 1854338496
from z=1 is vertex color: w
from z=1 is vertex name: 1854338496
from z=1 is vertex color: w
from z=2 is vertex name: 1854338496
from z=2 is vertex color: w
from z=2 is vertex name: 1854338496
from z=2 is vertex color: w
有人能帮我解释一下为什么只有getName()才会发生这种情况吗?
提前感谢!
更改构造函数
Vertex(int name)
{
name = name;
pred = NULL;
color = 'w';
desc = 1000000;
}
以下方式
Vertex(int name)
{
this->name = name;
pred = NULL;
color = 'w';
desc = 1000000;
}
或
Vertex(int name)
{
Vertex::name = name;
pred = NULL;
color = 'w';
desc = 1000000;
}
或
Vertex(int name) : name( name )
{
pred = NULL;
color = 'w';
desc = 1000000;
}
或
Vertex(int name) : name( name ), pred( NULL ), color( 'w' ), desc( 1000000 )
{
}
否则,隐藏类的数据成员name
的局部变量name
被分配给它自己。
此外,最好使用限定符const来声明所有getter。例如
int getName() const {return name;}
char getColor() const {return color;}
Vertex* getPred() const {return pred;}
int getDesc() const {return desc;}
构造函数中的变量name
隐藏成员name
。这样就可以将局部变量赋值给它自己。
要解决此问题,请写入this->name = name;
或更改参数的名称。
您也可以使用成员初始化列表,IMO是执行此操作的最佳方式。注意,无论初始化器在列表中的顺序如何,成员都将始终按照在类中声明的顺序进行初始化。
相关文章:
- 访问者访问变体并返回不同类型时出错
- 在Linux for Windows上编译C++代码时出错
- 读取文件的最后一行并输入到链接列表时出错
- 重载操作程序时出错>>用于类中的字符串 memebr
- 调用专用模板时出错"no matching function for call to [...]"
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- LINK 尝试使用 OpenSSL evp aes 256 c++ 时出错
- 在Google Kick start中提交时出错
- 在c++中访问int到类对象的映射时出错
- 分段错误当我试图运行程序时出错
- 使用dynamic_cast和构造函数时出错
- CHECK(调用)函数在Google Colab中出错
- 用pybind11包装C++抽象类时出错
- 为x86而非x64编译时出错
- 从R调用C++函数并对其进行集成时出错
- 这个函数哪里出错了
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 为重写std::exception的库生成swig接口时出错
- 导入/导出变量时出错
- PrintWindow函数在notepad.exe中出错