this指针
C ++有一个名为 "this" 的指针。"this" 返回自己的地址。
在某些情况下,"this" 可能是必要的,但经常使用它被认为是一种风格偏好。
请注意下面的程序,比较 Shape 自身区域的面积 和 shape 的面积:
//Use 'this' to compare areas
//The class functions
int compareWithThis(Shape shape)
{
//return the area of the calling shape
return this->Area() > shape.Area();
}
//Using the class function in a program
//In this case sh1.Area() is being compared to sh2.Area()
if(sh1.compareWithThis(sh2)) {
cout << "\nShape2 is smaller than Shape1" <<endl;
}
我可以执行完全相同的函数 而 不使用 " this " 。
//'this' is not necessary to compare shapes
int compare(Shape shapeIn)
{
return Area() > shapeIn.Area();
}
要使用类函数:
if(sh1.compare(sh2))
{
cout << "\nShape2 is smaller than Shape1" <<endl;
}
举例,同样,该函数将sh1.area() 与 sh2.area()的进行比较。
#include <iostream>
using namespace std;
class Shape {
public:
// Constructor definition
Shape(int l = 2, int w = 2)
{
length = l;
width = w;
}
double Area()
{
return length * width;
}
//Use 'this' to compare areas
int compareWithThis(Shape shape)
{
return this->Area() > shape.Area();
}
//'this' is not necessary to compare shapes
int compare(Shape shapeIn)
{
return Area() > shapeIn.Area();
}
private:
int length; // Length of a box
int width;
};
int main(void)
{
Shape sh1(4, 4); // Declare shape1
Shape sh2(2, 6); // Declare shape2
if(sh1.compare(sh2))
{
cout << "\nShape2 is smaller than Shape1" <<endl;
}
else
{
cout << "\nShape2 is equal to or larger than Shape1" <<endl;
}
if(sh1.compareWithThis(sh2)) {
cout << "\nShape2 is smaller than Shape1" <<endl;
}
else
{
cout << "Shape2 is equal to or larger than Shape1" <<endl;
}
return 0;
}
运行结果:
代码解析:
1。以下代码中,this->Area() 是什么意思呢?
//Use 'this' to compare areas
int compareWithThis(Shape shape)
{
return this->Area() > shape.Area();
}
我们先来看 " -> " 和 " . " 的区别:
" -> " 是指针类型,是指针引用;
" . " 是实例化对象,类中普通成员的引用;
我们举个小例子:
class student
{
public:
string name[20];
};
第一种情况,采用指针访问 student *xy,则访问时,需要写成 *xy.name="hhhhh"; 等价于 xy->name="hhhhh";
第二种情况,采用普通成员访问 student xy,则访问时,需要写成 xy.name="hhhhh";
所以,this 代表 *Shape,整个式子来看,this.Shape->Are() 代表 :*Shape.Are() 。
这里 this.Shape->Are() 的值就是:2 * 2 = 4;
解析完毕。
编程就是算法和数据结构,算法和数据结构是编程的灵魂。