c++ 构造函数constructor

版权声明:瞎几把写 https://blog.csdn.net/weixin_43184615/article/details/82911196

构造函数:每个类都分别定义了他的对象被初始化的方式,类通过一个或几个特殊的成员函数(member function)来控制其对象的初始化过程,这些函数叫做构造函数。

构造函数的任务是初始化类对象的数据成员(data member),一般就是private里定义的data member。

以下引用https://blog.csdn.net/onlyongwang/article/details/80558131文章的图片
在这里插入图片描述

以下采用有参构造函数,且参数无默认值进行举例。

#include<iostream>
#include<string>

using namespace std;

class Student{
private:
	string _name;
	int _age;
	int _score;
public:
	Student(string name, int age, int score);//申明构造函数

	void print(); //申明普通函数
};

//定义构造函数
Student::Student(string name, int age, int score)
{
	_name = name;
	_age = age;
	_score = score;
}
//定义普通函数
void Student::print(){
	cout << _name << "'s age is " << _age << " and the score is " << _score << endl;
}

//主函数调用开始
int main()
{
	Student stu("qingqing", 15, 99);//定义class Stuednt 名称为stu
	stu.print();  //调用print函数

	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_43184615/article/details/82911196
今日推荐