簡體   English   中英

聲明Get Method const時出現C ++錯誤

[英]C++ Error when declare Get Method const

C ++中的const問題...

MyVektor[i].getName().getFirstName()生成錯誤:(請參見下面的代碼)

Error 1 error C2662: 'Name::getFirstName' : cannot convert 'this' pointer from 'const Name' to 'Name &' c:\users\betula\documents\visual studio 2012\projects\c++laboration_2\c++laboration_2\person_test.cpp   215 1   C++Laboration_2

3   IntelliSense: the object has type qualifiers that are not compatible with the member function
            object type is: const Name  c:\Users\Betula\Documents\Visual Studio 2012\Projects\C++Laboration_2\C++Laboration_2\Person_Test.cpp   215 17  C++Laboration_2

PersonTest main調用Vector和Method ...

vector<Person> MyPersons;

ShowPerson(MyVektor);

方法:

void ShowPerson(vector<Person> &MyVektor)
{
cout << endl << " List of people: " << endl << endl;

for( size_t i = 0; i < MyVektor.size(); i++)
{
cout << " " + MyVektor[i].getName().getFirstName() + " " + MyVektor[i].getName().getLastName() << endl;

    //cout << " " + MyVektor[i].getAddress() + " " + MyVektor[i].getAddress()+ " " +     MyVektor[i].getAddress() << endl;

    cout <<" Social security number: " + MyVektor[i].getPersNr() << endl;

    cout <<" Shoe size: " + to_string(MyVektor[i].getSkoNr()) << endl << endl;  
    }
}

所有Getmethods都在類Person&Name中聲明const

const Name Person::getName()
{
return my_name;
}

const string Name::getFirstName()
{
return firstName;
}

如果我刪除類人和名稱中的const聲明,一切正常...

對初學者的任何建議...

/尼莫斯

const Name Person::getName()替換為Name Person::getName() const等,以使函數恆定,而不是返回變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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