虚拟重载运算符 >> 和 <<

Mar*_*ian 3 c++ virtual class operator-overloading function-definition

我需要一个需要其子类重载<<and的接口>>,但我不太确定如何重载,因为这些运算符没有作为成员函数重载:

std::istream& operator>> (std::istream& in, Student& student) {
    in >> student.name >> student.group;
    for (int& i : student.marks) { in >> i; }
    return in;
} 
Run Code Online (Sandbox Code Playgroud)

也许有办法使它成为成员函数?

Jef*_*ica 10

你可以这样做:

class StudentInterface
{
public:
    virtual void readSelfFrom(std::istream& in) = 0;
};

std::istream& operator>> (std::istream& in, StudentInteface& student) 
{
    student.readSelfFrom(in);
    return in;
} 
Run Code Online (Sandbox Code Playgroud)

然后让用户从 中派生StudentInterface,例如:

class Student: public StudentInterface
{
public:
    void readSelfFrom(std::istream& in) override
    {
        in >> name >> group;
        for (int& i : marks) { in >> i; }
    }
};
Run Code Online (Sandbox Code Playgroud)


Vla*_*cow 5

这种情况下的一般方法是在基类中声明一个虚拟成员函数,如

virtual std::ostream & out( std::ostream &os = std::cout ) const;
Run Code Online (Sandbox Code Playgroud)

在派生类中,该函数将被覆盖。

然后运算符 << 看起来像

std::ostream & operator <<( std::ostream &os, const Base &obj )
{
    return obj.out( os );
}
Run Code Online (Sandbox Code Playgroud)

类似的方法可以定义operator >>唯一在这种情况下虚拟成员函数不会是常量..