const与this指针

const是一个C语言(ANSI C)的关键字,具有着举足轻重的地位。它限定一个变量不允许被改变,产生静态作用。使用const在一定程度上可以提高程序的安全性和可靠性。另外,在观看别人代码的时候,清晰理解const所起的作用,对理解对方的程序也有一定帮助。

形式参数后加const

#if 0
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	int* getp() const //const object *const this

	{
		this->val = 100;//error
		ptr = nullptr;//error this->ptr=nullptr  不让改
		*ptr = 200;//ok
		return ptr;
	}


};
int main()
{
	int tmp = 10;
	object obj(& tmp);
	object objb(&tmp);
	obj.getp();//obj(this);
	return 0;
}
#endif


#if 0
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	const int* getp()   // object *const this

	{
		this->val = 100;//ok
		ptr = nullptr;//ok
		return ptr;
	}


};


int main()
{
	int tmp = 10;
	object obj(&tmp);
	object objb(&tmp);
	const int *p=obj.getp();//obj(this);
	//int* p = obj.getp();//error 

	return 0;
}
#endif

以引用返回

#if 1
class object
{
public:
	int* ptr;
	int val;
public:
	object(int* p) :ptr(p) {}
	 int*const & getp() const  //  int* & getp() const  return ptr会报错! // 

	{
		//this->val = 100;//ok
		//ptr = nullptr;//ok
		return ptr;
	}
};
int main()
{
	int tmp = 10;
	int x = 20;
	object obj(&tmp);
	object objb(&tmp);
	//const int* p = obj.getp();//obj(this);
	int* p = obj.getp();//error 
	p = &x;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
运算符重载是指在类中对C++内置运算符进行重新定义的过程,使得运算符能够适用于类对象。C++中的运算符重载可以通过成员函数和非成员函数两种方式实现。 this指针是一个指向当前对象的指针,它在成员函数中使用。在运算符重载中,this指针可以用来引用当前对象的成员变量和成员函数。 例如,在一个矩形类中重载“+”运算符,可以通过以下两种方式实现: 1. 成员函数方式: ```c++ class Rectangle { public: int width, height; Rectangle operator+(const Rectangle& other) { Rectangle result; result.width = this->width + other.width; result.height = this->height + other.height; return result; } }; ``` 在上述代码中,重载了“+”运算符,并使用了成员函数的方式实现。在函数中使用了this指针来引用当前对象的成员变量。 2. 非成员函数方式: ```c++ class Rectangle { public: int width, height; }; Rectangle operator+(const Rectangle& r1, const Rectangle& r2) { Rectangle result; result.width = r1.width + r2.width; result.height = r1.height + r2.height; return result; } ``` 在上述代码中,重载了“+”运算符,并使用了非成员函数的方式实现。在函数中没有使用this指针,而是直接引用了两个参数对象的成员变量。 总结:运算符重载中可以使用this指针来引用当前对象的成员变量和成员函数。但是,在非成员函数的方式中无法使用this指针,需要通过参数来引用对象的成员变量。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值