gpt4 book ai didi

c++ - 带有 Getter 函数的 C++ 中的错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:10:40 25 4
gpt4 key购买 nike

当我尝试显示一些信息时,我遇到了一个奇怪的错误。这是我的类(class)代码的一部分:

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

关于c++ - 带有 Getter 函数的 C++ 中的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29125040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com