【C++类和对象---const修饰成员函数 && 修饰成员】

构造析构函数不能加限定符

在实际开发中如果成员函数不会修改成员变量,就应该加上const,这是C++的编程规范,就像const修饰函数形参一样。后人看见成员函数有const修饰就不会修改成员变量

#include<iostream>
using namespace std;

class person {
public:
	string name;
	mutable int age;
	person(const string& name,const int& age) :name(name), age(age) {};

    void f(){};
	void show() const
	{ cout << name << " " << ++age;  //mutable可以突破const的限制 }

    void operator()() const
    {
      cout<<"operator_const"<<endl;
    }
    
    void operator()()
    {
      cout<<"operator"<<endl;
    }

};

int main()
{
	person p("西施", 19);
	p.show();
    
    p();     //仿函数
    
    person p2("貂蝉",18);
    p2()     //仿函数

	return 0;
}

mutable可以突破const的限制,被mutable修饰的成员变量,永远处于可变状态

1非const成员函数可以调用const和非const成员函数;const成员函数只能调用const成员函数

2非const对象可以调用const和非const成员函数;const对象只能调用const成员函数,在仿函数中同样适用

	person p("西施", 19);
	p.show();
	p.f();

	const person p2("貂蝉", 18);
	p2.show();
	//p2.f();  //err

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值