赞
踩
派生类的构造函数
看下面的代码
class Person{ private: char * m_name; public: Person(char* name):m_name(name) { } }; class Student :public Person { private: int m_age; public: Student(char* name,int age) :Person(name) ,m_age(age){} void Display() { cout << m_age << " " << m_name << endl; } }; int main() { Student stu("少爷",18); stu.Display(); return 0; }
运行结果
18 少爷
继承中构造函数的调用原则
1、子类对象创建时会首先调用父类的构造函数
2、父类的构造函数在执行结束后,在执行子类的构造函数
3、当父类的构造函数有参数时,需要在子类的初始化列表中显示调用
4、派生类不能调用间接基类的构造函数
派生类的析构函数
看下面的代码
class Person{ private: char * m_name; public: char * m_name; Person(){ cout << "Person()" << endl; } ~Person(){ cout << "~Person()" << endl; } }; class Student :public Person { private: int m_age; public: Student(){ cout << "Student()" << endl; } ~Student(){ cout << "~Student()" << endl; } }; int main() { Student stu; return 0; }
运行结果
Person()
Student()
~Student()
~Person()
请看下面的代码:
class Human{ public : void test(){ printf("human...\n"); } void destroy(){ delete this; } private: ~Human(){ printf("delete successful!...\n"); } }; int main(){ Human* hp=new Human(); hp->test(); hp->destroy(); return 0; }
运行结果
human...
delete successful!...
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。