// This program defines a person class which includes an
// overloaded insertion operator.
// Also included is a personDisplay manipulator
// that displays a message and sets a field size
// for the name
#include<iostream>
#include<fstream>
#include<string>
#include<iomanip>
using namespace std;
class Person
{
private:
int idNum;
string name;
public:
Person(const int, const string);
friend ostream& operator<<(ostream&, const Person&);
};
Person::Person(int id, string nm)
{
idNum = id;
name = nm;
}
ostream& operator<<(ostream& out, const Person& p)
{
out << p.name << " " << p.idNum << endl;
return out;
}
ostream& personDisplay(ostream& out, Person& p)
{
out << "Here is a person: ";
out.setf(ios::left);
out.width(12);
return out;
}
int main()
{
Person someBody(365, "Gabby");
cout << personDisplay << someBody << endl;
int dog;
cin >> dog;
return 0;
}
This program is supposed to output "Here is a person:...". instead it outputs "002A11DI...". It does output "Gabby 365". Please help me find the source of the error. Thank you for your help.
答案 0 :(得分:1)
呃我不知道从哪里开始。首先personDisplay
不是运算符重载。要调用此函数,您应该使用:
personDisplay(std::cout, someBody);
第二
std::cout << personDisplay () << ...
由于personDisplay()
返回out
所在的引用(地址),因此将打印“垃圾”。 (正如Igor Tandetnik在评论中所说)
您可以做的第三个也是唯一的选择是:
int main()
{
Person someBody(365, "Gabby");
personDisplay(std::cout, someBody)
cout << someBody << endl;
int dog;
cin >> dog;
return 0;
}