C++:常对象、方法

常对象只能调用常方法

#include<iostream>
using namespace std;

class Test
{
public:
	Test(int a, int b):mb(b)
	{
		ma = a;
		//mb = b;
	}
	void Show()
	{
		cout << "ma:" << ma << endl;
		cout << "mb:" << mb << endl;
	}
private:
	
	int ma;
	const int mb;
};

int main()
{
	const Test test1(10,20);//常对象
	test1.Show();
	return 0;
}

分析:

第一个const修饰的 test1 *this有间接修改的风险,所以编译器防止发生,直接杜绝掉。

修改:

	void Show()const
	{
		cout << "ma:" << ma << endl;
		cout << "mb:" << mb << endl;
	}

void Show()const   加const  此时Show是一个常方法

常方法:this类型: const Test* const

相当于  const Test* const this=&test1;

此时 *this被const修饰,没有被间接修改的风险,编译器允许通过。

常方法不能调用普通方法

void Show()const//常方法
{
	cout << "ma:" << ma << endl;
	cout << "mb:" << mb << endl;
        /**错误**/
	//Show(ma);
	//this->Show(ma); //  常方法this指针类型 const Test* const
	(*this).Show(ma);//左边是常对象,常对象不能调用普通方法
}

void Show(int a)
{
	cout << "ma:" << ma << endl;
	cout << "mb:" << mb << endl;
}

 //Show(ma);
 //this->Show(ma); // 常方法this指针类型 const Test* const
(*this).Show(ma); //左边是常对象,常对象不能调用普通方法

常方法里面的this指针指向的是常对象,常对象不能调用普通方法。

普通对象可以调用常方法

int main()
{
	Test test2(10,20);
	test2.Show();//普通对象可以调用常方法
	return 0;
}

Test test2(10,20);//普通对象
test2.Show();
这里相当于:const Test* const this=&test2;

普通方法可以调用常方法

void Show()const//常方法
{
	cout << "ma:" << ma << endl;
	cout << "mb:" << mb << endl;
}

void Show(int a)
{
	cout << "ma:" << ma << endl;
	cout << "mb:" << mb << endl;
	(*this).Show();
}

普通方法里的this指针指向的是普通对象 ,普通对象可以调用常方法。

猜你喜欢

转载自blog.csdn.net/free377096858/article/details/85344057