c++ - 模板运算符返回对抽象类的引用

标签 c++ templates operators abstract-class

伙计们,为什么这段代码不起作用?

template <typename t>
class Abstract
{
public:
   ~Abstract(){}
   virtual Abstract<t>& operator +(Abstract<t>&) = 0;
};

template <typename t>
class Not_Abstract : public Abstract
{
t* tab; //let Not_Abstract store an array of objects of type t, whatever
public:
  ~Not_Abstract(){ delete[] tab; }
  Not_Abstract<t>& operator +(Not_Abstact<t>&);
};

虽然我不知道既然引用是一个指针,但我不知道,两个运算符的定义是等价的;但它们似乎是独立的功能。是否可以采取任何措施来在“抽象”中保留虚拟运算符并仍然使代码正常运行?

最佳答案

both operator's definitions are equivalent

不,他们不是。一个有一个 Abstract& 参数,另一个有一个 Not_Abstract& 参数。要重写,参数类型必须匹配,以便重写可以以与其重写的函数相同的方式调用。

Is there anything that can be done to retain virtual operator in "Abstract" and still have the code functioning?

覆盖必须采用 Abstract&,并且无论是否使用 Non_Abstract 调用它都要做正确的事情。

关于c++ - 模板运算符返回对抽象类的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28370644/

相关文章:

c# - 如何在执行相同功能时避免 C# 中的短路评估

java - x > -1 vs x >= 0,是否存在性能差异

c++ - 无法识别的命令行选项 '-std=c++11'

c++ - 为什么这个模仿 `vector` 的迭代器初始化的构造函数可以工作?

c++ - C/C++ 标识符和文件名中的 camelCase 与 snake_case

c++ - 如何调用模板方法?

c++ - 提升 : dereference a template argument if it's a pointer

C++:重载运算符=

c++ - 最简单的二叉树插入不起作用

c++ - 我怎样才能让编译器告诉我什么文件 #define 一个值?