#include <iostream>
#include <string>
using namespace std;
class Person
{
string name;
public:
Person():name("")
{
cout << "Person default ctor\n";
}
Person(const string& name_in):name(name_in)
{
cout << "Person string ctor: " << name << "\n";
}
~Person()
{
cout << "Person dtor: " << name << "\n";
}
string get_name()
{
return name;
}
};
class Professor:public Person
{
int office;
public:
Professor(const string& name_in, int office_in):Person(name_in), office(office_in)
{
cout << "Professor string ctor: " << get_name() << endl;
}
~Professor()
{
cout << "Professor dtro: " << get_name() << endl;
}
};
int main()
{
Person alice("Alice");
Professor bob("Bob", 10);
return 0;
}
我假设输出应该是:
Person string ctor: Alice
Person dtor: Alice
Professor string ctor: Bob
Professor dtor: Bob
因为这似乎应该从程序的结构逻辑上遵循。然而,真正的输出是:
Person string ctor: Alice
Person string ctor: Bob
Professor string ctor: Bob
Professor dtor: Bob
Person dtor: Bob
Person dtor: Alice
有人可以解释这是为什么吗?我对类/构造函数/析构函数有什么不了解,这让我想出了错误的输出?