C++模板类继承和运算符使用

标签 c++ templates operators

我有一个模板类,它定义了适用于模板参数的运算符。 我有另一个类继承自这个类,我当然希望操作符被继承。

考虑一下:

template <typename T>
class A
{
public:
  A(const T& x) : x_(x) {}
  A operator-(const A& other) 
  { 
    A r(*this);
    r.x_ -= other.x_;
    return r;
  }

  T x() const { return x_; }

private:
  T x_;
};

template <typename T>
class B : public A<T>
{
  // additional stuff here
};

我似乎无法将 A 中声明的任何运算符用于 B 类型的对象。

示例:

int main()
{
  // Fine
  A<int> a(5);
  A<int> b(2);
  A<int> c = a - b;
  std::cout << c.x() << std::endl;

  // Won't compile :( 
  B<int> d(5);
  B<int> e(2);
  B<int> f = d - e;
  std::cout << f.x() << std::endl;

  return 0;
}

将触发以下错误:错误:请求从“A”转换为非标量类型“B”

有什么办法可以实现这一点吗?我真的想避免在 B 类中重写所有代码(完全相同)。

谢谢!

最佳答案

问题不在于调用运算符,而在于构造 B返回值是 A .

如果B不包含除其基类 A 之外的任何数据,您可以为 B 提供构造函数来自A :

template <typename T>
class B : public A<T>
{
public:
     B(const T& x) : A<T>(x) {}
     B(const A<T>&x) : A<T>(x) {}
  // additional stuff here
};

如果B确实包含自己的数据,那么您肯定需要实现 operator-处理那些数据字段?

关于C++模板类继承和运算符使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8059629/

相关文章:

c++ - 在今天的 C++ 中,构造 fstream 时我能否可靠地得到错误?

javascript - 如何将javascripts发送到底部? (在 symfony 2 中)

c - 了解 C 中包含 '++' 和 '->' 运算符的表达式的计算

javascript - 尝试从函数返回有效的电子邮件

mysql - SQL 使用 OR & AND 运算符(新手)

c++ - std::rethrow_exception 和抛出的异常类型

c++ - 当 C++ 标准提供将名称带入全局命名空间的 C header 时,这是否包括重载?

c++ - 如何从 fork 中检索类的实例?

templates - 混合模板 : how to halt compilation?

c++ - 返回 nullptr 迭代器,如何转换它们