const数据成员的初始化;const成员函数;const对象与非const对象

const数据成员的初始化;const成员函数;const对象与非const对象,第1张

const数据成员初始化;const成员函数;const对象与非const对象

一,const数据成员的初始化方式:

1.使用类内值(C++11支持)
2.使用构造函数的初始化列表
(如果同时使用这两种方式,以初始化列表中的值为最终初始化结果)
注意: 不能在构造函数或其他成员函数内,对const成员赋值!

对于非const的类静态成员,只能在类的实现文件中初始化。
const类静态成员,可以在类内设置初始值,也可以在类的实现文件中设置初始值。(但是不要同时在这两个地方初始化,只能初始化1次)详细内容请看另一篇博客《静态数据成员与静态成员函数》

类内初始值:
所在文件:Human.h

class Human {
public:
	//...
	int getAge();
	string getName();
	int getSalary();
	void description();
private:
	string name;
	int age = 0;
	int salary;
	char* addr;
	
	//设置代表血型的变量bloodType的类内初始值
	const string bloodType = "A";
};

构造函数的初始化列表:
i) 自定义的默认构造函数
ii) 自定义的重载构造函数

i) 自定义的默认构造函数
所在文件:Human.cpp

//初始化列表
Human::Human():bloodType("未知") {
	name = "Evan";
	age = 24;
	salary = 30000;
	strcpy(addr, "China");
}

void description() {
	cout << "name: " << name
		<< "  age: " << age
		<< "  salary: " << salary
		<< "  地址:" << addr
		<< "  血型:" << bloodType << endl;
}

ii) 自定义的重载构造函数
所在文件:Human.cpp

//初始化列表
Human::Human(int age, int salary, string bldType):bloodType(bldType) {
	name = "Evan";
	this->age = age;
	this->salary = salary;
	strcpy(addr, "China");
}

void description() {
	cout << "name: " << name
		<< "  age: " << age
		<< "  salary: " << salary
		<< "  地址:" << addr
		<< "  血型:" << bloodType << endl;
}

访问const数据成员:
所在文件:main.cpp

int main(void) {
	Human h1;
	Human h2(24, 40000, "O");
	
	h1.description();
	h2.description();

	//或者使用指针
	Human *p = &h1;
	Human *p2 = &h2;
	
	p->description();
	p2->description();
}

二,const成员函数

const成员函数不能修改数据成员的数据内容

所在文件:Human.h

class Human {
public:
	//...
	int getAge();
	string getName();
	int getSalary();
	
	//const成员函数
	void description const();
private:
	string name;
	int age = 0;
	int salary;
	char* addr;
	
	//设置代表血型的变量bloodType的类内初始值
	const string bloodType = "A";
};

所在文件:Human.cpp

void Human::description() const {
	strcpy(addr, "Usa"); //可以修改指针的内容,但是不可以修改指针的地址
	//salary = 3;

	cout << "name: " << name
		<< "  age: " << age
		<< "  salary: " << salary
		<< "  血型:" << bloodType
		<< "  地址:" << addr << endl;
	//cout << this << endl;
}

void description const();的实现中,

void Human::description() const {
	strcpy(addr, "Usa"); //允许,合法
	addr = "USA"; //不允许,非法
	salary = 3; //不允许,非法
	...
}

可以修改指针指向的内容,但是不可以修改指针的地址!

三,const对象与非const对象

类Human中,只有成员函数void description const();,是const成员函数!

所在文件:main.cpp

int main(void) {
	cosnt Human h1;
	Human h2;
	
	h1.description(); //允许,合法
	h1.getName(); //不允许,非法

	h2.description(); //允许,合法
	h2.getName(); //允许,合法
}

因此可知,const对象只能访问const成员函数;
非const对象即可以访问const成员函数,也可以访问非const成员函数!

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5691495.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存