[英]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声明所有的获取方法。 例如
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的最佳方法。 这样,请注意,无论列表中初始化程序的顺序如何,成员将始终按照在类中声明的顺序进行初始化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.