c++--this指针

this指针,在成员函数中使用,指代的是当前对象

#include <iostream>using namespace std;class Box
{public:// 构造函数定义//默认初始值,定义时没有赋值的情况下使用 Box(double l=2.0, double b=2.0, double h=2.0){cout <<"Constructor called." << endl;length = l;breadth = b;height = h;}void out(void){//成员函数函数中可直接使用这些变量 cout << length << endl;cout << breadth << endl;cout << height;} double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();//this表示当前对象 //return整个表达式,这边返回值实在if中 }int demo(void){this->out();cout << "\nnow start others.\n";return this->Volume();} private://成员函数和友元函数可使用 double length;     // Length of a boxdouble breadth;    // Breadth of a boxdouble height;     // Height of a box
};//初始化之后 
int main(void)
{Box Box1(3.3, 1.2, 1.5);    // Declare box1Box Box2(8.5, 6.0, 2.0);    // Declare box2Box Box3;Box1.out();cout << "\n=========\n";Box3.out();cout << "\n-------------\n";int a = Box3.demo();cout << "a = " << a;cout << "\n-=-=-=-=-=-=-=-\n";if(Box1.compare(Box2)){cout << "Box2 is smaller than Box1" <<endl;}else//运行的是这个 {cout << "Box2 is equal to or larger than Box1" <<endl;}return 0;
}

结果:

c++--this指针

this指针,在成员函数中使用,指代的是当前对象

#include <iostream>using namespace std;class Box
{public:// 构造函数定义//默认初始值,定义时没有赋值的情况下使用 Box(double l=2.0, double b=2.0, double h=2.0){cout <<"Constructor called." << endl;length = l;breadth = b;height = h;}void out(void){//成员函数函数中可直接使用这些变量 cout << length << endl;cout << breadth << endl;cout << height;} double Volume(){return length * breadth * height;}int compare(Box box){return this->Volume() > box.Volume();//this表示当前对象 //return整个表达式,这边返回值实在if中 }int demo(void){this->out();cout << "\nnow start others.\n";return this->Volume();} private://成员函数和友元函数可使用 double length;     // Length of a boxdouble breadth;    // Breadth of a boxdouble height;     // Height of a box
};//初始化之后 
int main(void)
{Box Box1(3.3, 1.2, 1.5);    // Declare box1Box Box2(8.5, 6.0, 2.0);    // Declare box2Box Box3;Box1.out();cout << "\n=========\n";Box3.out();cout << "\n-------------\n";int a = Box3.demo();cout << "a = " << a;cout << "\n-=-=-=-=-=-=-=-\n";if(Box1.compare(Box2)){cout << "Box2 is smaller than Box1" <<endl;}else//运行的是这个 {cout << "Box2 is equal to or larger than Box1" <<endl;}return 0;
}

结果: