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
来自in PersonTest
...的向量和方法调用
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 都声明为 const i 类 Person & Name
const Name Person::getName()
{
return my_name;
}
const string Name::getFirstName()
{
return firstName;
}
如果我删除类 Person & Name 中的 const 声明一切正常......
对初学者有什么建议...
/尼莫斯