C++ 类继承与构造函数:深入解析 Dog 类与 Animal 类的关系
#include
using namespace std;
class Animal // 鐖剁被 鍩虹被 { public: Animal(int age) : m_age(age) { cout << "Animal" << endl; } ~Animal() { cout << "~Animal" << endl; } int m_age; protected: int m_pro; private: int m_pri; };
class Dog : public Animal // 缁ф壙 瀛愮被/娲剧敓绫? { public: //Dog(int age = 1) { //error Dog(int age = 1) : Animal(age) { m_age = age; cout << "Dog" << endl; } ~Dog() { cout << "~Dog" << endl; } // Animal an; };
int main() { cout << sizeof(Dog) << endl; Dog wc; return 0; }
解释这个程序为什么不能设置age=0内容:这个程序不能设置age=0是因为在 Dog 类的构造函数中,调用了 Animal 类的构造函数,并将 age 作为参数传递给了 Animal 类的构造函数。而在 Animal 类的构造函数中,将传递的 age 赋值给了 m_age 成员变量。如果将 age 设置为 0,则在 Animal 类的构造函数中,m_age 的值也会被设置为 0。所以,不能设置 age=0,否则会影响到 Animal 类的 m_age 成员变量的值。
原文地址: https://www.cveoy.top/t/topic/qsd7 著作权归作者所有。请勿转载和采集!