过载<运算符和继承类 [英] overloading << operators and inherited classes

查看:140
本文介绍了过载<运算符和继承类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类,然后几个派生类。我想重载<这些派生类的操作符。对于正常的操作符,即'+',虚函数做的伎俩。我理解的标准约定是声明

I've got a base class and then several derived classes. I would like to overload the "<<" operator for these derived classes. For normal operators, i.e. '+', virtual functions do the trick. What I understand to be the standard convention is to declare

friend ostream& operator<<(ostream& out, MyClass& A);

,然后在类之后定义函数。事先我会认为添加虚拟到上面的定义会使它的工作,但经过一些想法(和我的编译器的错误),我意识到,这没有什么意义。

within my class and then define the function after the class. A priori I would think adding virtual to the above definition would make it work, but after some thought (and errors from my compiler) I realize that doesn't make much sense.

我在一个测试用例上尝试了一个不同的粘连,所有的类成员都是公开的。例如:

I tried a different tack on a test case, where all the class members are public. For example:

class Foo{
 //bla
};

ostream& operator<<(ostream& out, Foo& foo){
  cout << "Foo" << endl;
  return foo;
}

class Bar : public Foo{
 //bla
};

ostream& operator<<(ostream& out, Bar& bar){
  cout << "Bar" << endl;
  return bar;
}

///////////////////////

Bar bar = Bar();
cout << bar << endl; // outputs 'Foo', not 'Bar' 

- 基类操作符<正在被调用而不是派生类操作符。在上面的例子中,如何为派生类调用正确的操作符get?更普遍的是,如果我的类有私有成员我想保护,我如何纠正操作符重载使用friend关键字?

So in some way this is "polymorphism gone bad" -- the base class operator<< is being called rather than the derived class operator. In the above example, how do I make the correct operator get called for the derived class? And more generally, if my class has private members I want to protect, how can I correct the operator overloading while using the friend keyword?

推荐答案

您可以使用虚拟助手函数。这里是一个完全未经测试的例子,所以请理解任何语法错误:

You can use a virtual helper function. Here's a completely untested example, so excuse any syntax mistakes:

virtual ostream& Foo::print(ostream& out) const {
    return out << "Foo";
}

virtual ostream& Bar::print(ostream& out) const {
    return out << "Bar";
}

// If print is public, this doesn't need to be a friend.
ostream& operator<<(ostream& out, const Foo& foo) {
    return foo.print(out);
}

编辑:根据@

这篇关于过载&lt;运算符和继承类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆