“When a member function is called, how does C++ keep track of which object it was called on?”. The answer is that C++ utilizes a hidden pointer named “this”!
“当调用成员函数时,C++如何跟踪调用它的对象?”。答案是C++使用了一个名为“this”的隐藏指针!
#include <stdio.h>
class Pointer{
int x,y,z;
public:
static double pi;
Pointer(int a,int b,int c):x(a),y(b),z(c){}
int getx(){ // 隐含const this指针,引用当前类的实例变量。
return x;
}
int gety() const; // 隐含const int* const this指针
int getz() const{ // 隐含const int* const this指针
return this->z;
}
Pointer& operator=(Pointer& others) // 隐含const this指针
{
x = others.x;
y = others.y;
this->z = others.z;
return *this;
}
static double getpi() // no this pointer
{
return pi;
}
};
double Pointer::pi = 3.141592;
int Pointer::gety() const{ // 隐含const int* const this指针
return this->y;
}
int gety(const Pointer *ths){
return ths->gety();
}
int main()
{
Pointer pt(3,4,5);
printf("%d\n",pt.gety()); // 4
printf("%d\n",gety(&pt)); // 4
printf("%f\n",Pointer::getpi());// 3.141592
getchar();
}
When overloading an operator using a member function:
使用成员函数重载运算符时:
The overloaded operator must be added as a member function of the left operand.
重载运算符必须作为左操作数的成员函数添加。
The left operand becomes the implicit *this object
左操作数成为隐式*this对象
All other operands become function parameters.
所有其他操作数都成为函数参数。
#include <iostream>
class Cents
{
private:
int m_cents;
public:
Cents(int cents) : m_cents(cents) { }
// Overload Cents + int
Cents operator+ (int value); // implicitly const this
int getCents() const { return m_cents; }
};
// note: this function is a member function!
// the cents parameter in the friend version is now the implicit *this parameter
Cents Cents::operator+ (int value) // implicitly const this
{
return Cents(m_cents + value); //this->m_cents
}
int main()
{
Cents cents1(6);
Cents cents2(cents1 + 2);
std::cout << "I have " << cents2.getCents() << " cents.\n"; // I have 8 cents.
getchar();
return 0;
}
It can sometimes be useful to have a class member function return the object it was working with as a return value. The primary reason to do this is to allow a series of member functions to be “chained” together, so several member functions can be called on the same object!
有时,让类成员函数将其处理的对象作为返回值返回会很有用。这样做的主要原因是允许将一系列成员函数“链接”在一起,以便可以在同一对象上调用多个成员函数!
By having functions that would otherwise return void return *this instead, you can make those functions chainable. This is most often used when overloading operators for your classes.
通过使用返回*this代替返回void的函数,您可以使这些函数可链接。这在重载类的运算符时最常用。
#include <iostream>
class Calc
{
private:
int m_value;
public:
Calc(int a):m_value(a){};
Calc& add(int value) { m_value += value; return *this; }
Calc& sub(int value) { m_value -= value; return *this; }
Calc& mult(int value) { m_value *= value; return *this; }
int getValue() { return m_value; }
};
int main()
{
Calc calc(0);
calc.add(5).sub(3).mult(4);
std::cout << calc.getValue() << '\n'; // 8
getchar();
}
ref
https://www.learncpp.com/cpp-tutorial/the-hidden-this-pointer/
_End_