带有Getter函数的C++中出错

Error in C++ with a Getter function

本文关键字:出错 C++ Getter 函数 带有      更新时间:2023-10-16

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

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是执行此操作的最佳方式。注意,无论初始化器在列表中的顺序如何,成员都将始终按照在类中声明的顺序进行初始化。