gpt4 book ai didi

c++ - 重载 = 运算符(operator),无法让它工作

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:42:30 26 4
gpt4 key购买 nike

我试图在下面的代码中重载第 9 行的 =operator:

void searchContact(vector<Person> &people){
string searchTerm;
vector<Person>::iterator it;

cout << endl;
cout << "Enter search term: ";
getline(cin, searchTerm);

it = find(people.begin(), people.end(), searchTerm);

if (it != people.end()){
cout << "Element found in: " << *it << '\n';
}else{
cout << "Element not found\n";
}
}

我的做法是这样的:

  int data;

Person& operator=(Person& a) { return a; }
Person& operator=(int a) {
data = a;
return *this;
}

我收到这个错误:

class.cpp:129:30: error: ‘Person& operator=(Person&)’ must be a nonstatic member function
Person& operator=(Person& a) { return a; }
^
class.cpp:130:26: error: ‘Person& operator=(int)’ must be a nonstatic member function
Person& operator=(int a) {

我的方法有什么问题,还是我从一开始就做错了?

最佳答案

首先,您重载了错误的运算符。 std::find()使用 operator== (比较)而不是 operator= (任务)。而且,鉴于您正在传递 std::stringstd::find() , 你需要一个 operator==这需要 std::string作为输入,不是 Person .

其次,您正在尝试将运算符实现为一元运算符,这意味着它们必须是您的 Person 的非静态成员。类(class)。编译器提示他们不是。

三、如果std::find()找到匹配项,您正在传递 *itstd::cout , 所以你需要一个重载的 operator<<这需要 Person用于输出。

尝试这样的事情:

class Person
{
public:
...

bool operator==(const string &rhs) const
{
// compare members of *this to rhs as needed...
return ...; // true or false
}

/* alternatively:
friend bool operator==(const Person &lhs, const string &rhs)
{
// compare members of lhs to rhs as needed...
return ...; // true or false
}
*/

friend ostream& operator<<(ostream &out, const Person &p)
{
// output p to out as needed...
return out;
}

...
};

然后您的搜索代码将起作用:

void searchContact(vector<Person> &people)
{
cout << endl;
cout << "Enter search term: ";

string searchTerm;
getline(cin, searchTerm);

vector<Person>::iterator it = find(people.begin(), people.end(), searchTerm);

if (it != people.end()) {
cout << "Element found in: " << *it << '\n';
} else {
cout << "Element not found\n";
}
}

关于c++ - 重载 = 运算符(operator),无法让它工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46921979/

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