给定一个类,例如:
class Person
{
private:
char *name;
public:
Person()
{
name = new char[20];
}
~Person()
{
delete [] name;
}
}
我想使用如下语句从 this 的一个实例打印名称:
cout << myPerson << endl;
我需要做什么来定义 <<
此类的输出运算符?
最佳答案
在类中添加:
friend std::ostream& operator<< (std::ostream& out, const Person& P);
然后定义运算符<<是这样的:
std::ostream& operator<< (std::ostream& out, const Person& P) {
out << P.name;
return out;
}
关于c++ - 如何在 C++ 中定义特定于类的 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/907620/