栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

构造函数和析构函数

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

构造函数和析构函数

#include 
#include 

using namespace std;

class Student {
private:
	int number;
	char* name;
	int age;
	float score;
public:
	Student();//默认构造函数
	Student(int no, const char* n, int a, float s);//带参构造函数
	Student(Student& s);//拷贝构造函数
	~Student();//析构函数
	
	void show();
};

Student::Student() {//默认构造函数
	number = 0;
	name = NULL;
	age = 0;
	score = 0;
}

Student::Student(int no, const char* n, int a, float s) {//带参构造函数
	number = no;
	name = new char[strlen(n) + 1];
	strcpy_s(name, strlen(n) + 1, n);
	age = a;
	score = s;
}

Student::Student(Student& s) {//拷贝构造函数
	number = s.number;
	name = new char[strlen(s.name) + 1];
	name = s.name;
	age = s.age;
	score = s.score;
}

Student::~Student() {//析构函数
	
	if (name != NULL) {
		cout << name << "同学分解掉" << endl;
	}
	else {
		cout << "有一个同学即将退出" << endl;
	}
}

void Student::show() {
	if (name != NULL) {
		cout << "学号:" << number << "t";
		cout << "姓名:" << name << "t";
		cout << "年龄:" << age << "t";
		cout << "成绩:" << score << endl;
	}
}

int main(void) {
	
	Student zhangsan(1, "张三", 20, 97);
	Student lisi(2, "李四", 21, 100);
	zhangsan.show();
	lisi.show();

	Student anonymous(zhangsan);
	anonymous.show();

	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/289528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号