【发布时间】: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