![](/img/trans.png)
[英]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.