声明Get Method const时出现C ++错误

时间:2013-05-15 10:27:43

标签: c++ 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

来自main的{​​{1}}的向量和方法调用...

PersonTest

方法:

vector<Person> MyPersons;

ShowPerson(MyVektor);

所有Getmethods都声明const我有类Person&amp;名称

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

如果我删除类Person&amp;中的const声明命名一切正常......

对初学者的任何建议......

/ Nimos

1 个答案:

答案 0 :(得分:4)

const Name Person::getName()替换为Name Person::getName() const等,使函数保持不变,而不是返回变量。