this 指针是必须的吗?

善良超锅锅 2011-07-16 11:29:43
this指针是必须的?我才看this指针,好像在一个程序中我去掉了this指针编译器也不会报错,运行结果也和有this指针时一样。
this指针难道只是为了代码的可读性,还是我还没学到它必要的地方。
#include<iostream>
class Rectangle{
public:
unsigned width,height;
Rectangle(unsigned width=0,unsigned height=0);
void setSize(unsigned width,unsigned height);
unsigned area();
unsigned perimeter();
bool isSquare();
};
Rectangle::Rectangle(unsigned width,unsigned height){
this->width=width; //这里的this指针我去掉也没什么不同啊
this->height=height; //
}
void Rectangle::setSize(unsigned width,unsigned height){
this->width=width;
this->height=height;
}
unsigned Rectangle::area(){
return (width*height);
}
unsigned Rectangle::perimeter(){
return (width+width+height+height);
}
bool Rectangle::isSquare(){
if(width==height){return true;}
else{return false;}
}
int main()
{
unsigned width=9;
unsigned height=42;
std::cout<<"with a width of "<<width<<" and a height of "<<height<<"...\n\n";
Rectangle myRectangle(width,height);
std::cout<<"The perimeter of rectangle is "<<myRectangle.perimeter()<<"\n";
std::cout<<"The area of rectangle is "<<myRectangle.area()<<"\n";
std::cout<<"This rectangle ";
if(myRectangle.isSquare()){
std::cout<<"is also ";}
else{std::cout<<"is not ";}
std::cout<<" a square.\n\n";
std::cout<<"Press Enter or Return to continue.\n";
std::cin.get();
return 0;
}
...全文
122 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
bdmh 2011-07-16
  • 打赏
  • 举报
回复
去掉一样,this是隐含的
善良超锅锅 2011-07-16
  • 打赏
  • 举报
回复
意思说我可以不用this指针,编译器会自己隐性调用吗?
那我以后都不调用行吗?
老邓 2011-07-16
  • 打赏
  • 举报
回复
this指针难道只是为了代码的可读性,还是我还没学到它必要的地方。
=======
this指针的使用本身是必须的。
只是编译器(语法)支持隐式调用。

unsigned Rectangle::area(){
return (width*height);
}
相当于:

unsigned Rectangle::area(){
return (this->width*this->height);
}
老邓 2011-07-16
  • 打赏
  • 举报
回复
width=width; //这里的this指针我去掉也没什么不同啊
等价于:this->width=width;
碎炎 2011-07-16
  • 打赏
  • 举报
回复
this指针还是挺重要的 你要明白调用成员函数的时候会传入一个this指针
序员 2011-07-16
  • 打赏
  • 举报
回复
成员变量和参量名字一样,感觉这样做很不好
Syudf 2011-07-16
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 loaden 的回复:]
this指针难道只是为了代码的可读性,还是我还没学到它必要的地方。
=======
this指针的使用本身是必须的。
只是编译器(语法)支持隐式调用。

unsigned Rectangle::area(){
return (width*height);
}
相当于:

unsigned Rectangle::area(){
return (this->width……
[/Quote]
隐式调用this指针,为了好读,易于维护,使用显示调用为好:this->width = width;
Xomic 2011-07-16
  • 打赏
  • 举报
回复
this 指针是对象创建是隐藏指向该对象的

简单举个例子,如果要返回该对象的地址呢?return this; this就不可少了!

至善者善之敌 2011-07-16
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 shimachao 的回复:]
意思说我可以不用this指针,编译器会自己隐性调用吗?
那我以后都不调用行吗?
[/Quote]

恩,没错,不过为了看起来结构清晰明了,一般还是加上THIS

64,635

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧