【问题标题】:polymorphism with abstract class on coutcout 上具有抽象类的多态性
【发布时间】:2015-11-14 17:51:53
【问题描述】:

我有抽象类(“父亲”类)和子类

我想在父亲身上写上操作符

这里是代码

#include <iostream>

using namespace std;

class father {
    virtual friend ostream& operator<< (ostream & out, father &obj) = 0;

};

class son: public father  {
    friend ostream& operator<< (ostream & out, son &obj)
    {
        out << "bla bla";
        return out;
    }
};
void main()
{
    son obj;
    cout << obj;

}

我得到 3 个错误

错误 3 错误 C2852 : 'operator

错误 2 错误 C2575 : 'operator

错误 1 ​​错误 C2254:'

请问我能做什么?

【问题讨论】:

  • 全局函数不能是纯虚函数。
  • 如果我想在标题上写“
  • 你可以提供一个protected纯虚函数std::ostream&amp; put(std::ostream&amp; os) const = 0;和一个全局函数friend ostream&amp; operator&lt;&lt; (ostream &amp; out, father &amp;obj)来使用它。请注意,friend 关系不会被继承。

标签: c++ class polymorphism operator-overloading


【解决方案1】:

虽然你不能让操作符virtual,你可以让他们调用一个普通的虚函数,像这样:

class father {
    virtual ostream& format(ostream & out, father &obj) = 0;
    friend ostream& operator<< (ostream & out, father &obj) {
        return format(out, obj);
    }
};

class son: public father  {
    virtual ostream& format(ostream & out, son &obj) {
        out << "bla bla";
        return out;
    }
};

现在只有一个operator &lt;&lt;,但是father的每个子类都可以通过重写虚成员函数format来提供自己的实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多