E0349扩展istream以支持Person类时出错

E0349 Error while Extending istream to support a Person class

本文关键字:出错 Person 支持 扩展 istream E0349      更新时间:2023-10-16

我尝试了使用和不使用#include <iostream>#include <string>甚至using namespace std,但没有任何变化。参数必须是引用。当尝试运行代码时,我收到以下错误:第9行中的E0349 no operator ">>" matches these operands

#include <iostream>
#include <string>
#include "Person.h"
#include <cstdio>
using namespace std;
//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
is >> p.getName() >> p.getAge();
return is;
}
//Extending ostream to support the Person class
std::ostream & operator<<(std::ostream & os, Person & p) {
os << "[" << p.getName()<<"," << p.getAge()<<"]";
}
int main() {
Person *pOne = new Person();
cout << "Person1's name is: " << pOne->getName() << endl;
cin >> *pOne;
getchar(); //Just to leave the console window open
return 0;
}

个人代码:

#pragma once
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
short age;
public:
Person();
virtual ~Person();
Person(string, short);
string getName();
short getAge();
};

这里是Person.cpp的代码:

#include "Person.h"
#include <iostream>
#include <string>
using namespace std;
Person::Person()
:name("[Unassigned Name]"), age(0)
{
cout << "Hello from Person::Person" << endl;
}
Person::~Person()
{
cout << "Goodbye from Person::~Person" << endl;
}
Person::Person(string name, short age)
:name(name), age(age)
{
cout << "Hello from Person::Person" << endl;
}
string Person::getName()
{
return this->name;
}
short Person::getAge()
{
return this->age;
}

is后面第9行的第一个>>是红色下划线。我使用的是Visual Studio 2017社区。

问题是运算符>>需要一些可以更改的东西。像getName这样的函数的返回值不是这样的。

以下是通常的操作方法,即使运算符>>成为一个友元函数,以便它可以直接访问Person类的内部。

class Person
{
// make operator>> a friend function
friend std::istream & operator>>(std::istream & is, Person & p);
private:
string name;
short age;
public:
Person(string, short);
string getName();
short getAge();
};
//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
is >> p.name >> p.age;
return is;
}

但不是唯一的办法。这是另一种不需要使任何东西成为朋友函数的方法。它使用临时变量,然后从这些临时变量中生成并分配一个Person对象。

//Extending istream to support the Person class
std::istream & operator>>(std::istream & is, Person & p) {
string name;
short age;
is >> name >> age;
p = Person(name, age);
return is;
}