重载类的输出流运算符
Overloading the Output Stream Operator for a Class
假设这是我的类:
class Student {
std::string name;
int CWID;
public:
Student(std::string name = "N/A", int CWID = 99999999) : this->name(name), this->CWID(CWID) {}
};
现在,我如何重载将打印类中所有数据的输出流运算符<<
。我猜这相当于Java中的toString()
方法,但请告诉我如何在C++中做到这一点。
将返回名称和CWID的成员函数添加到类中。
std::string getName() const {return name;}
int getCWID() const {return CWID;}
然后,添加一个非成员函数,将数据写入流。
std::ostream& operator<<(std::ostream& out, Student const& s)
{
return out << s.getName() << " " << s.getCWID();
}
以下是您的操作方法:
class Student {
std::string name;
int CWID;
public:
Student(std::string name = "N/A", int CWID = 99999999) : name(name), CWID(CWID) {}
friend std::ostream& operator<<(std::ostream& stream, const Student& student);
};
std::ostream& operator<<(std::ostream& stream, const Student& student)
{
stream << '(' << student.name << ", " << student.CWID << ')';
return stream;
}
请注意,这个重载函数不是类的一部分。
您可以编写非成员函数
std::ostream& operator<<(std::ostream& os, const Student& stud)
{
os << stud.name << " " << stud.CWID;
return os;
}
并将其声明为类中的友元函数
class Student {
std::string name;
int CWID;
public:
Student(std::string name = "N/A", int CWID = 99999999) : this->name(name), this->CWID(CWID) {}
friend ostream& operator<<(ostream& os, const Student& stud);
};
相关文章:
- 如何在C++中编写 ostream 的向量,它接收所有不同的输出流,如 cout、ostringstream 和 ofs
- 在输出流中插入换行符
- 在类外部重载输入和输出流
- 通用容器的输出流
- 我的动态链接队列在同一输出流中调用时不正确地输出三个返回函数
- 使输出流式处理运算符适用于 boost::variant<std::vector<int>、int、double 的正确方法是什么>
- 获取C++输出流中元素的大小
- 用于了解输入和输出流缓冲区实际工作方式的程序
- 控制多线程程序中的输出流
- 为什么输出流首选" "而不是""?
- C++ 输出流运算符 <<() 中的字符何时加宽?
- 音频缓冲区列表,用于输出流格式已压缩的 AUHAL 单元
- 如何为提升日志和自定义类型定义输出流运算符
- C++ 中的递增/递减和输出流运算符优先级
- 输出流中的运算符优先级C++
- 输出流运算符的重载
- 重载类的输出流运算符
- C++ 编译器选择输出流运算符<<的错误重载
- C++:输入和输出流运算符:关联性
- 如何使用标头中定义的输出流运算符