我是靠谱客的博主 独特自行车,这篇文章主要介绍C++之类的const成员变量和成员函数2,现在分享给大家,希望可以做个参考。

在C++之类的const成员变量和成员函数中,我们在Student类中,声明了一个const成员变量max_length,每一个类的对象都初始化为同一个固定的值。而我们通常需要每一个类的对象都要初始为不同的const成员变量。

以下面为例:const成员变量school,一旦初始化,就不可以更改了。具有const成员变量时,必须采用参数初始化列表写构造函数

class Student{
private:
	string name;
	int age;
	float score;
	//const成员变量
	const string school;
	//定义静态成员变量
	static int number; 
	static float total;
public:
	//Student(string name,int age,float score);
	//有const成员变量,必须有参数初始化列表,
	Student(string name,int age,float score,string s):name(name),age(age),score(score),school(s){
		number++;
		total += score;
	}
	//拷贝构造函数中,const成员变量的初始化,用初始化列表
	Student(const Student & s):school(s.school){
		this ->name = s.name;
		this ->age = s.age;
		this ->score = s.score;
		number++;
		total += score;
	};
	~Student();
	void setSchool(string s);
	void setName(string n);
	string getName()const;
	void setAge(int a);
	int getAge() const;
	void setScore(float s);
	float getScore() const;
	void say() const;
	static float getAverage();
	
	//运算符的重载
	//bool operator== (const Student &s) const;
	//用友元函数重载等于 运算符
	friend bool operator== (const Student &s,const Student&s1);
};


 我们看到构造函数 
必须使用参数初始化列表: 

	//有const成员变量,必须有参数初始化列表,
	Student(string name,int age,float score,string s):name(name),age(age),score(score),school(s){
		number++;
		total += score;
	}

//拷贝构造函数中,const成员变量的初始化,用初始化列表
	Student(const Student & s):school(s.school){
		this ->name = s.name;
		this ->age = s.age;
		this ->score = s.score;
		number++;
		total += score;
	};

而不能采用以下的方式,进行

	Student(string name,int age,float score,string s):name(name),age(age),score(score){
<span style="white-space:pre">		</span>school = s;
		number++;
		total += score;
	}




最后

以上就是独特自行车最近收集整理的关于C++之类的const成员变量和成员函数2的全部内容,更多相关C++之类内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(68)

评论列表共有 0 条评论

立即
投稿
返回
顶部