【发布时间】:2022-06-22 23:37:01
【问题描述】:
我有一个类似这样的代码:
template <typename T>
struct B
{
B &operator =(const T &) { return *this; }
};
struct D : B<int> {};
int main()
{
D d;
d = 0;
return 0;
}
失败的:
error: no viable overloaded '='
d = 0;
~ ^ ~
note: candidate function (the implicit copy assignment operator) not viable: no known conversion from 'int' to 'const D' for 1st argument
struct D : B<int> {};
^
note: candidate function (the implicit move assignment operator) not viable: no known conversion from 'int' to 'D' for 1st argument
struct D : B<int> {};
^
这个错误很容易发现和理解:D 缺少与int 的赋值运算符,即使它的基类有它。从c++11 开始,我们可以解决这个问题,将赋值运算符从基础对象“提升”到派生对象:
struct D : B<int> { using B::operator =; /* Easy fix! */ };
但我正在处理一个c++98 项目,因此此修复程序不可用。在 C++11 之前这是如何解决的?
【问题讨论】:
-
听起来很奇怪。 using 侦探来自早期的 C++。你在 C++98 中遇到什么错误?也许
using B<int>::operator =;会起作用。 -
对于 C++98,
using B<int>::operator=;为我工作。 -
在此上下文中使用
using指令是C++11 feature。
标签: c++11 c++98 c++ inheritance operator-overloading c++98