C ++中的显式上传

时间:2015-07-14 13:12:08

标签: c++ inheritance casting

鉴于类ABC的定义为

#define SET_COPY(T, A) T(T const&) = A; T& operator=(T const&) = A
#define SET_MOVE(T, A) T(T&&) = A; T& operator=(T&&) = A
#define SET_COPY_MOVE(T, A, B) SET_COPY(T, A); SET_MOVE(T, B)

struct A
{
    int n;

    A(int n2 = 0)
    : n(n2)
    {
    }

    SET_COPY_MOVE(A, delete, default);
};

struct B
{
    int n;

    B()
    {
    }

    B(A const& a)
    : n(a.n)
    {
    }

    SET_COPY_MOVE(B, delete, default);
};

struct C : A, B
{
    C()
    : B(static_cast<A const&>(*this)) // [1]
    {
        static_cast<B&>(*this) = B(); // [2]
    }
};

在大多数情况下,上传是隐含的,例如

A a = C();
B b = C();

因为C同时是AB

但是我不能把[1]写成

: B(*this)

我无法将[2]写为

*this = B();

static_cast<B>(*this) = B(); // [3]
  1. 为什么要在[1][2]
  2. 中明确指出
  3. 为什么[3]没有编译?

3 个答案:

答案 0 :(得分:0)

首先是不可编译的,因为编译器不知道,你要调用什么构造函数,你有3个构造函数。

B(const A&)
B(B&&)
B(const B&)

并且编译器无法选择,因为C可以投放到AB

其次,因为没有赋值运算符C& operator = (const B&)

第三个无法编译,因为您无法为临时变量分配内容,而static_cast<B>(*this)创建类型为B的临时对象作为(* this)的副本。

答案 1 :(得分:0)

只需编译有问题的代码并查看编译器的错误消息! 我用gcc为你做了这个结果:

[1] error: call of overloaded 'B(C&)' is ambiguous
       B(*this) // [1]
[2] error: no match for 'operator=' (operand types are 'C' and 'B')
      *this = B(); // [2]

应该几乎是自我解释。

答案 2 :(得分:0)

  

在大多数情况下,上传是隐含的,例如

A a = C();
B b = C();

请注意,这不是一个向上的。这是一个切片。您正在切出临时对象的一部分并分配给每个变量。

也许你的意思。

 A const& a = C();  // need to use a reference to catch the C
 B const& b = C();  // Also because it is a temporary you need to use const