【问题标题】:constructors and inheritance. Why does 'class derivedInstance()' not call derived constructor [duplicate]构造函数和继承。为什么“类派生实例()”不调用派生构造函数[重复]
【发布时间】:2020-07-02 08:20:52
【问题描述】:

我再次关注继承和虚拟化,我错误地使用括号在 main 中创建了派生的孙对象,“ryan”。

当我去掉 () 参数括号时,它第二次运行良好,但是当我使用 () 时,它跳过了孙子的构造函数,以及所有其他构造函数和析构函数。

有人可以解释一下这里发生了什么,我认为这仍然可以正常工作。

#include <iostream>

class Base {
public:
    int age=5;

    Base() {std::cout << "Base Created" << std::endl;}
    virtual ~Base() { std::cout << "Base Deleted" << std::endl; }


};

class son : public virtual Base {
public:
  //  int age = 1;
  son(std::string name) { std::cout <<"son created" << std::endl; }
  son() { std::cout << "son created - default constructor" << std::endl; }
  ~son() { std::cout << "son deleted" << std::endl; }

};



class sonwife : public virtual  Base {
public:
   // int age = 2;
    sonwife() { std::cout << "son wife created - default constructor" << std::endl; }

    sonwife(std::string name) { std::cout << "son wife created" << std::endl; }

    ~sonwife() { std::cout << "sons wife deleted" << std::endl; }

};

class grandchild : public  sonwife, public  son
{
public:
    grandchild() { std::cout << "Grand child created" << std::endl; 
    std::cout << age;
    }

    ~grandchild() { std::cout << "grand child gone!" << std::endl; }
};


int main()
{
    Base *b = new son("Ryan");
    delete b;
    grandchild ryan; // vs. grandchild ryan();
    return 0;
}

【问题讨论】:

  • fwiw 与 Base b();Base b; 的情况相同。考虑阅读minimal reproducible example,因为它将帮助您和其他人发现代码中的错误。

标签: c++ constructor polymorphism virtual


【解决方案1】:

grandchild ryan(); 声明了一个名为 ryan 的 函数,它不接受任何参数并返回一个孙子。它没有声明名为 ryan 的变量。

显然,当 ryan 是一个函数时,没有构造函数调用。

【讨论】:

  • 在这种时候,我们真的需要模因。谢谢。哈
猜你喜欢
  • 2013-04-05
  • 2018-07-21
  • 2012-12-19
  • 1970-01-01
  • 2016-07-19
  • 2015-11-03
  • 2012-11-06
  • 2013-01-28
  • 1970-01-01
相关资源
最近更新 更多