gpt4 book ai didi

声明 Get 方法 const 时出现 C++ 错误

转载 作者:行者123 更新时间:2023-11-27 23:15:39 24 4
gpt4 key购买 nike

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

PersonTestmain 的 vector 和方法调用...

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 there class Person & Name

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

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

如果我删除 Class Person & Name 中的 const declare,一切正常...

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

/尼莫斯

最佳答案

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

关于声明 Get 方法 const 时出现 C++ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16562629/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com