【发布时间】:2015-06-02 12:50:02
【问题描述】:
我有一个包含三个类(A、B 和 C)的类层次结构。 A 和 B 是基类,使用派生类型进行参数化。 C 类派生自 A 和 B。
B 类为 A 类型的对象提供了一个赋值运算符,而 C 类通过 using super::operator= 声明继承了这个赋值运算符。
当我从 A 类型的对象定义类 B 中的构造函数时,我在 Visual Studio 2013 中得到 错误: 两个重载具有相似的转换 (C2666),但是我在 gcc (4.8.2)、clang (3.4) 和 intel icc (Studio 2015) 中没有收到任何错误或警告。 (用-Wall -pedantic编译)
这里是简化的例子:
template <class Model> struct A {};
template <class Model> struct B
{
B() {}; // default constructor
// copy constructor for objects of type A
template <class M>
B(A<M> const&) {}
// assignment operator for objects of type A
template <class M>
Model& operator=(A<M> const& rhs)
{
return static_cast<Model&>(*this);
}
};
struct C : public B<C>, public A<C>
{
typedef B<C> super;
// copy assignment operator
C& operator=(C const& rhs) { return *this; }
// adopt assignment operator for A<C> from super-class
using super::operator=;
};
int main()
{
C c;
A<C> a;
c = a;
}
如果我将模板化类 A 替换为非模板化类,它也可以在 Visual Studio 中无错误地编译 - 但这不是可以解决的方法。
我的问题是:这个结构在符合标准的意义上是格式良好的,还是错误消息正确? B 中复制构造函数的 explicit 之类的说明符是否有助于解决问题?
顺便说一句:在 Visual Studio 中,我收到 警告:指定了多个赋值运算符 (C4522),因为 C 类中的复制赋值运算符。有人可以向我解释一下,为什么这会是个问题?
【问题讨论】:
标签: c++ inheritance copy-constructor assignment-operator using-declaration