[英]c++ why I do not get compile error when I call non const method from ref member inside const method
[英]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.