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;
}