常数据成员 ,常函数

版权声明:lixiang666 https://blog.csdn.net/weixin_43838785/article/details/90579424

常数据成员通过初始化列表初始化,不可被修改

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class Circle {
public:
	Circle(double con_radius);
	double circumference();
private:
	double m_fradius;
	const double PI;
};
Circle::Circle(double con_radius) :PI(3.14)
{
	m_fradius = con_radius;
}
double Circle::circumference()
{
	return 2 * PI*m_fradius;
}
int main()
{
	Circle c1(2);
	cout << "circumference:" << c1.circumference() << endl;
	system("pause");
	return 0;
}

常成员函数可以访问非const数据成员,但不可修改
非const成员函数可以读取常数据成员,但不可修改
常成员函数不可以用非const成员函数。

若定义的是常对象,则只能调用常成员函数,常对象要进行初始化
定义常对象的一般形式为:
类名 const 对象名[(实参表列)];
也可以把const写在最左面:
const 类名 对象名[(实参表列)];
二者等价。

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
using namespace std;
class Student {
public:
	Student(string con_name, int con_ID);
	~Student();
	string get_stdname() const;
	void print_stdname();
private:
	string m_strName;
	int m_nID;
};
Student::Student(string con_name, int con_ID):m_strName(con_name)
{
	m_nID = con_ID;
}
Student::~Student()
{
}
string Student::get_stdname() const
{
	return m_strName;
}
void Student::print_stdname()
{
	cout << "std's name:" << m_strName << endl;
}
int main()
{
	Student std_tom("ToM",20);
	std_tom.print_stdname();
	cout << std_tom.get_stdname() << endl;
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43838785/article/details/90579424
今日推荐