文章标题
来源:互联网 发布:淘宝一元起拍靠谱吗 编辑:程序博客网 时间:2024/06/11 07:15
#include <iostream>#include <string>using namespace std;class Base{public: Base() { cout << "Base::基类" << endl; } ~Base() { cout << "调用基类的析构函数" << endl; }; // 成员初始化列表语法 Base(string x,string y):x(x),y(y) { cout << "Base::传递参数的基类构造函数" << endl; };private: string x; string y;};class Derive:public Base // 派生 公有派生// 使用公有派生,基类的公有成员将成为派生类的公有成员。// 基类的私有部分也将成为派生类的一部分,但只能通过基类的公有和保护方法访问。// 派生类不能直接访问基类的私有成员,而必须通过基类方法进行访问。{public: Derive() { cout << "Derive::派生" << endl; } ~Derive() { cout << "调用派生类的析构函数" << endl; }; // 成员初始化列表语法 Derive(string z,string str2,string str3):Base(str2,str3),z(z) { //this.z = z; cout << "Derive::传递参数的派生类的构造函数" << endl; } Derive(string z,const Base & base):Base(base),z(z) { cout << "Derive::传递参数的派生类的构造函数" << endl; }private: string z;};int main(){ // 基类对象应该在程序进入派生类构造函数之前被创建。 Derive *derive; derive = new Derive("10","10","10"); delete derive; cout << endl; cout << "********************" << endl; Base *base = new Base("20","20"); derive = new Derive("BG_80",*base); //delete base; // 派生类过期时,程序首先调用派生类的析构函数,然后调用基类的析构函数。 delete derive; // 这里要不要delete base? 应该不要 system("pause"); return 0;}
如果子类中没有默认无参构造函数,那么像下面这样调用会报错
#include <iostream>using namespace std;class A{public: int a; int b;// A()// {// cout<<"A Constructed 1\n";// }A(int a,int b){ this->a=a; this->b=b; cout<<"A Constructed 2\n";}};class B:public A{public: int c; int d;B(){ cout<<"B Constructed 1\n";}B(int c,int d):A(100,200){ this->c=c; this->d=d; cout<<"B Constructed 2\n";}};int main(){ // B b(1,1); // cout << "b.a = " << b.A::a <<" " << "b.b = " << b.A::b << endl; // cout << "b.a = " << b.a <<" " << "b.b = " << b.b << endl; // cout << "b.c = " << b.c <<" " << "b.d = " << b.d << endl; B b; return 0;}
0 0
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- ocp-137
- JavaScript表达式计算 eval
- ocp-138
- ocp-139
- HDU 2295 Radar (DLX求重复覆盖, A*搜索)
- 文章标题
- 关于软件测试的个人思考
- Android中SimpleAdapter详解
- 欢迎使用CSDN-markdown编辑器
- 链表创建、反转
- Sublime快捷键
- poj1930
- 网络编程(5)——HttpURLConnection/HttpClient的区别
- 在ubuntu下对stm32开发板的编译、烧写、调试