【问题标题】:What is the syntax for calling a base class's value constructor with a base class pointer?使用基类指针调用基类的值构造函数的语法是什么?
【发布时间】:2020-02-09 21:06:08
【问题描述】:

基类有一个接受参数的值构造函数。它没有默认构造函数。

下面使用了一个base 类指针,它设置为等于堆上某个derived 类对象的地址。这显式调用了derived 的值构造函数。有没有办法在这一行显式调用base 的值构造函数?我理解另一种选择是您可以让派生类构造函数调用基类构造函数。

base *ptr = new derived(args);

【问题讨论】:

  • 不,C++ 不能以这种方式工作。只有派生类的构造函数调用基类的构造函数。您提到的“替代方案”是 C++ 工作的唯一方式。
  • @SamVarshavchik 我认为他可以通过使用using Base::Base; 来使用它,但是这里的两个构造函数有一个 arg,所以是一个新的歧义。
  • @asmmo 在这种情况下,派生构造函数仍然隐藏基,如果它们具有完全相同的签名(成员函数的 using-declaration 与块范围 using-declaration 的工作方式不同)

标签: c++ inheritance constructor


【解决方案1】:

您可以在您的行中显式调用base 的值构造函数,如下所示(但请注意参数列表不同)

   #include<iostream>

    class Base{

    public:
        Base(int arg){std::cout<<"\nBase constructor";}
        Base()=default;
        virtual ~Base(){}
    };

    class Derived:public Base{
    public:
        Derived(double arg){
            std::cout<<"\nDerived constructor";
        }
        using Base::Base;//This is the key for the answer

    };


    int main(){

        Base* derivedPtr1 {new Derived{0.2}};//calls derived ctor
        Base* derivedPtr2 {new Derived{2}};//calls base ctor
        delete derivedPtr2;
        delete derivedPtr1;

    }

没有默认ctor的代码

#include<iostream>

class Base{

public:
    Base(int arg){std::cout<<"\nBase constructor";}
    virtual ~Base(){}

};

class Derived:public Base{
int k{};
public:
    Derived(double arg):Base(2){
        std::cout<<"\nDerived constructor";
    }
    using Base::Base;
    Derived()=default;
    ~Derived(){std::cout<<"\nDerived destructor";}

};


int main(){

    Base* derivedPtr1 {new Derived{0.2}};
    Base* derivedPtr2 {new Derived{2}};
    delete derivedPtr2;
    delete derivedPtr1;

}

【讨论】:

  • 有趣的是,如果 BaseDerived 构造函数的参数都是 int a 会怎样?程序将如何决定调用哪一个?你能明确地告诉程序调用哪一个吗?
  • @TedLyngmo OP 似乎要求动态分配
  • @David 如果Derived 使用相同的签名进行重载,这将隐藏基类中的函数,因此如果您实例化Derived,它将使用Derived 的构造函数.
  • @TedLyngmo 是的,这是个好主意。 (顺便说一句,删除基指针是未定义的行为,否则不一定“只调用基类析构函数”)。
  • 抱歉,我只专注于介绍using @TedLyngmo
猜你喜欢
  • 2010-09-12
  • 2021-09-09
  • 2013-01-28
  • 2020-03-17
  • 2011-02-12
  • 1970-01-01
  • 2018-07-16
  • 2012-06-24
相关资源
最近更新 更多