我有一个模板类,它定义了适用于模板参数的运算符。 我有另一个类继承自这个类,我当然希望操作符被继承。
考虑一下:
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/