编程语言
首页 > 编程语言> > C++类继承的构造拷贝析构函数

C++类继承的构造拷贝析构函数

作者:互联网

代码-F

#include<iostream>
using namespace std;
class zhu {
public: zhu(int a, int b=7) :X(a), Y(b) {}//不存在默认构造函数时
		zhu(zhu &a) { X = a.X; Y = a.Y; }
	void printfpoint() { cout << X <<"."<< Y << endl; }
	~zhu() { cout << "第一个类的析构函数" << endl; cin.get(); }
private:int X, Y;
};
class jia :public zhu {
public: jia(int x,int y) :zhu(x),a(y) {}//此时派生类构造函数的声明
		void printfmath() { cout << a << endl; }
		jia(jia &a) :zhu(a) {}
		~jia() { cout << "第二个类的析构函数" << endl; }
private:int a=6;
};
int main()
{	jia a(3,9);
	a.printfpoint();
	a.printfmath();
	jia b(a);
	b.printfpoint();
	b.printfmath();
	return 0;
}

代码-S

#include<iostream>
using namespace std;
class zhu {
public:                   //基类存在默认构造函数时
	void printfpoint() { cout << X <<"."<< Y << endl; }
	~zhu() { cout << "第一个类的析构函数" << endl; cin.get(); }
private:int X=1, Y=2;
};
class jia :public zhu {
public: jia(int x) :a(x) {}//派生类构造函数的声明
		jia(jia &a) { a = a.a; }
		~jia() { cout << "第二个类的析构函数" << endl; }
		void printfmath() { cout << a << endl; }
private:int a=0;
};
int main()
{	jia a(9);
	a.printfpoint();
	a.printfmath();
	//jia b(a);
	//b.printfpoint();
	//b.printfmath();
	return 0;
}

End

~
记录留存

嗨~辰 发布了8 篇原创文章 · 获赞 0 · 访问量 46 私信 关注

标签:zhu,cout,int,namespace,C++,析构,拷贝,include,构造函数
来源: https://blog.csdn.net/weixin_44228006/article/details/104095072