簡體   English   中英

帶有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聲明所有的獲取方法。 例如

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM