相关疑难解决方法(0)

为什么隐式复制构造函数调用基类复制构造函数而定义的复制构造函数不?

考虑一个类层次结构,其中A是基类并B派生自A.

如果未定义复制构造函数B,编译器将合成一个.调用时,此复制构造函数将调用基类复制构造函数(即使是合成的构造函数,如果用户没有提供).

#include <iostream>

class A {
    int a;
public:
    A() {
        std::cout << "A::Default constructor" << std::endl;
    }

    A(const A& rhs) {
        std::cout << "A::Copy constructor" << std::endl;
    }
};

class B : public A {
    int b;
public:
    B() {
        std::cout << "B::Default constructor" << std::endl;
    }
};

int main(int argc, const char *argv[])
{
    std::cout << "Creating B" << std::endl;
    B b1;
    std::cout << "Creating …
Run Code Online (Sandbox Code Playgroud)

c++ language-design copy-constructor

35
推荐指数
2
解决办法
1万
查看次数

如何从派生类复制构造函数中调用基类复制构造函数?

就像在标题中一样,如何从派生类复制构造函数中调用基类复制构造函数?

c++ inheritance constructor copy-constructor

15
推荐指数
2
解决办法
3万
查看次数

为什么不隐式调用基类的复制构造函数?

根据我的理解,当创建派生类的对象时,基类构造函数会自动调用(如果存在没有参数的构造函数)。复制构造函数似乎不是这种情况:

#include <iostream>

class Base
{
public:

    Base() 
    { 
        std::cout << "Base Constructor called" << std::endl; 
    }   

    Base(const Base& ref)
    {
        std::cout << "Base Copy Constructor called" << std::endl; 
    }
};

class Derived : Base
{
public:

    Derived() 
    { 
        std::cout << "Derived Constructor called" << std::endl; 
    }

    Derived(const Derived& ref) //: Base(ref) // <- without this Base copy constructor doesnt get called
    {
        std::cout << "Derived Copy Constructor called" << std::endl; 
    }
};

int main()
{
    Derived d1;

    Derived d2 …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance copy

0
推荐指数
1
解决办法
58
查看次数