重载类的输出流运算符

Overloading the Output Stream Operator for a Class

本文关键字:运算符 输出流 重载      更新时间:2023-10-16

假设这是我的类:

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);
};