重载类的输出流运算符

时间:2015-04-08 17:55:37

标签: c++

假设这是我的班级:

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 ++中完成它。

3 个答案:

答案 0 :(得分:1)

将成员函数添加到返回名称和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();
}

答案 1 :(得分:0)

您可以编写非会员功能

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

答案 2 :(得分:0)

以下是您的操作方法:

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

请注意,此重载功能不属于该类。