C++ E0349扩展istream以支持Person类时出错
我尝试了使用和不使用C++ E0349扩展istream以支持Person类时出错,c++,visual-studio,C++,Visual Studio,我尝试了使用和不使用#include#include甚至使用命名空间std的,但没有任何更改。参数必须是引用。尝试运行代码时,我收到以下错误:E0349没有运算符“>>”与第9行中的这些操作数匹配 #include <iostream> #include <string> #include "Person.h" #include <cstdio> using namespace std; //Extending istream to support the
#include
#include
甚至使用命名空间std的,但没有任何更改。参数必须是引用。尝试运行代码时,我收到以下错误:E0349没有运算符“>>”与第9行中的这些操作数匹配
#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;
}
#包括
#包括
#包括“Person.h”
#包括
使用名称空间std;
//扩展istream以支持Person类
std::istream&operator>>(std::istream&is、Person&p){
is>>p.getName()>>p.getAge();
回报是;
}
//扩展ostream以支持Person类
std::ostream&operator问题是operator>>需要一些它可以改变的东西。像getName
这样的函数的返回值不是这样的
下面是您通常的做法,即使operator>>成为朋友函数,以便它可以直接访问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;
}
getName()
getAge()
函数返回什么?请按要求在此处发布。getName()返回字符串成员变量名,getAge返回短成员变量age。这些是否作为引用返回?否则,这些函数将无法接收任何输入。我认为请不要将这些代码输入到您的计算机中!非常感谢你真的帮助了我!
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;
}
//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;
}