声明Get方法const时出错



c++中的const问题…

MyVektor[i].getName().getFirstName()产生错误:(见下面的代码)

Error 1 error C2662: 'Name::getFirstName' : cannot convert 'this' pointer from 'const Name' to 'Name &' c:usersbetuladocumentsvisual studio 2012projectsc++laboration_2c++laboration_2person_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:UsersBetulaDocumentsVisual Studio 2012ProjectsC++Laboration_2C++Laboration_2Person_Test.cpp   215 17  C++Laboration_2

mainPersonTest中的向量和方法调用…

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

所有的getmethod都声明为const i class Person &名称

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

如果我删除const声明在类Person &

对于初学者有什么建议吗?

/尼莫地平

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

最新更新