overloading #39;lt;lt;#39; with inheritance and polymorphism?(是否使用继承和多态性重载#39;lt;lt;#39;?)
                            本文介绍了是否使用继承和多态性重载';<;<;';?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
以下是代码外观的粗略示例,问题是如何让DerivedOne和DerivedTwo拥有重载的<;<;运算符,而将这些对象存储在Base*的向量中。
至于我要实现的目标;我希望能够遍历对象向量,并输出我在DerivedOne和DerivedTwo中告诉它的信息。
vector<Base*> objects;
class Base
{
 private:
 object Data
 public:
 object getData() { return Data; }
};
class DerivedOne : public Base
{
}
class DerivedTwo : public Base
{
}
现在我知道有这个,但它不会达到我的目的。
friend ostream &operator<<(ostream &stream, Object object)
{
    return stream << "Test" << endl;
}
推荐答案
Make your virtual methods private to separate how an object is used from how its behavior can be customized by derived classes.
这里有一个类似于其他答案的解决方案,但虚拟方法是私有的:
#include <iostream>
namespace {
  class Base {
    // private (there is no need to call it in subclasses)
    virtual std::ostream& doprint(std::ostream&) const = 0;
  public:
    friend std::ostream& operator << (std::ostream& os, const Base& b) {
      return b.doprint(os); // polymorphic print via reference
    }
    virtual ~Base() {} // allow polymorphic delete
  };
  class DerivedOne : public Base {
    std::ostream& doprint(std::ostream& os) const {
      return os << "One";
    }
  public:
    DerivedOne() { std::cerr << "hi " << *this << "
"; } // use << inside class
    ~DerivedOne() { std::cerr << "bye " << *this << "
"; }
  };
}
示例
#include <memory>
#include <vector>
int main () {
  using namespace std;
  // wrap Base* with shared_ptr<> to put it in a vector
  vector<shared_ptr<Base>> v{ make_shared<DerivedOne>() };
  for (auto i: v) cout << *i << " ";
  cout << endl;
}
输出
hi One
One 
bye One
                        这篇关于是否使用继承和多态性重载';<;<;';?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:是否使用继承和多态性重载';<;<;';?
				
        
 
            
        
             猜你喜欢
        
	     - 将函数的返回值分配给引用 C++? 2022-01-01
 - 将 hdc 内容复制到位图 2022-09-04
 - 使用 __stdcall & 调用 DLLVS2013 中的 GetProcAddress() 2021-01-01
 - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值 2021-01-01
 - XML Schema 到 C++ 类 2022-01-01
 - 如何提取 __VA_ARGS__? 2022-01-01
 - GDB 不显示函数名 2022-01-01
 - DoEvents 等效于 C++? 2021-01-01
 - OpenGL 对象的 RAII 包装器 2021-01-01
 - 哪个更快:if (bool) 或 if(int)? 2022-01-01
 
						
						
						
						
						