Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用“继承基类的复制和移动构造函数”;使用;关键词_C++_Inheritance_Copy Constructor_Move Constructor - Fatal编程技术网

C++ 使用“继承基类的复制和移动构造函数”;使用;关键词

C++ 使用“继承基类的复制和移动构造函数”;使用;关键词,c++,inheritance,copy-constructor,move-constructor,C++,Inheritance,Copy Constructor,Move Constructor,我想使用和关键字继承基类的复制构造函数: #include <iostream> struct A { A() = default; A(const A &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; } A( A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl;

我想使用
关键字继承基类的复制构造函数:

#include <iostream>

struct A
{
    A() = default;

    A(const A  &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; }
    A(      A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; }

    A& operator=(const A  &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
    A& operator=(      A &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
};

struct B : A
{
    using A::A;
    using A::operator=;

    B& operator=(const B  &) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
    B& operator=(      B &&) { std::cerr << __PRETTY_FUNCTION__ << std::endl; return *this; }
};

int main()
{
    A a;
    B b;
    b = a; // OK
    B b1(          a ); // compile error
    B b2(std::move(a)); // compile error
    return 0;
}
为什么我可以继承赋值运算符,但不能继承复制构造函数?有什么区别?如果我不能继承赋值运算符,我可以理解。但相反地继承赋值运算符被认为是可以的。这对我来说有点奇怪

故事

我想要的类似于问题中的问题:我只想向现有类添加新方法,而不修改它(它是来自另一个库的类)

:

#包括
结构A//不是我的类
{
};
结构B:A
{
使用A::A;
使用::运算符=;

void foo(){std::cerr您需要一个B的构造函数,它有一个as参数。然后您需要使默认构造函数显式

struct B : A
{
    using A::A;
    using A::operator=;

    B() = default;
    B(const A& a) : A(a) {}
    B(A &&a): A(std::move(a)) {}
};

Pretty_函数不是标准的。@JiveDadson,但它仍然很漂亮。在我的编译器上不是。它丢失了。因为标准是这样说的。“如果从基类引入派生类的构造函数或赋值运算符具有派生类的复制/移动构造函数或赋值运算符的签名(15.8),using声明本身不会抑制派生类成员的隐式声明;基类中的成员被隐式声明的派生类的复制/移动构造函数或赋值运算符隐藏或重写。很抱歉,这是一个错误的对正方式!因为“具有派生类的复制/移动构造函数或赋值运算符的签名”。它适用于
a::a(const B&)
,但不适用于这种情况。正确的理由是。请注意,它只适用于构造函数,不适用于赋值运算符。我不需要添加默认的显式构造函数。没有它()。将构造函数从
A
添加到
B
是我试图避免的。在添加一行代码
B(const A&A):A(A){}
之后,确实需要显式地创建默认构造函数,这是必需的。接受它或不接受它。我不知道。我刚刚向您展示了一个示例,它在没有
B()的情况下可以编译=默认值;
。但可能是gcc扩展。无论如何,您都有答案。祝您好运。
#include <iostream>

struct A // not my class
{
};

struct B : A
{
    using A::A;
    using A::operator=;

    void foo() { std::cerr << "fuu" << std::endl; }
};

A NotMyFunc()
{
    return {};
}

int main()
{
    B b(NotMyFunc());
    b.foo();
    return 0;
}
struct B : A
{
    using A::A;
    using A::operator=;

    B() = default;
    B(const A& a) : A(a) {}
    B(A &&a): A(std::move(a)) {}
};