C++中this指针的使用

Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.

Friend functions do not have a this pointer,because friends are not members of a class. Only member functions have a this pointer.

The this pointer is a pointer accessible only within the nonstatic member functions of a class, struct, or union type. It points to the object for which the member function is called. Static member functions do not have a this pointer.

         一个对象的this指针并不是对象本身的一部分,不会影响sizeof(对象)的结果。this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对象本身的地址作为一个隐含参数传递给函数。也就是说,即使你没有写上this指针,编译器在编译的时候也是加上this的,它作为非静态成员函数的隐含形参,对各成员的访问均通过this进行。

this指针是类的一个自动生成、自动隐藏的私有成员,它存在于类的非静态成员函数中,指向被调用函数所在的对象。全局仅有一个this指针,当一个对象被创建时,this指针就存放指向对象数据的首地址。

this指针使用场景:(1)、在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this;(2)、当参数与成员变量名相同时,如this->n = n(不能写成n = n)。

         The this pointer's type can be modified in the function declaration by the const and volatile keywords. To declare a function as having the attributes of one or more of these keywords, add the keyword(s) after the function argument list.

以下是测试代码:

this_pointer.hpp:

#ifndef FBC_MESSY_TEST_THIS_POINTER_HPP
#define FBC_MESSY_TEST_THIS_POINTER_HPP

#include 

// reference: http://www.tutorialspoint.com/cplusplus/cpp_this_pointer.htm
class Box
{
public:
	// Constructor definition
	Box(double l = 2.0, double b = 2.0, double h = 2.0)
	{
		std::cout << "Constructor called." << std::endl;
		length = l;
		breadth = b;
		height = h;
	}
	double Volume()
	{
		return length * breadth * height;
	}
	int compare(Box box)
	{
		return this->Volume() > box.Volume();
	}
private:
	double length;     // Length of a box
	double breadth;    // Breadth of a box
	double height;     // Height of a box
};

/*void Date::setMonth(int mn)
{
	month = mn; // These three statements are equivalent
	this->month = mn;
	(*this).month = mn;
}*/

// reference: https://msdn.microsoft.com/en-us/library/y0dddwwd.aspx
class Buf
{
public:
	Buf(char* szBuffer, size_t sizeOfBuffer);
	Buf& operator=(const Buf &);
	void Display();

private:
	char* buffer;
	size_t sizeOfBuffer;
};

// reference: http://en.cppreference.com/w/cpp/language/this
class T
{
	int x;

	void foo()
	{
		x = 6;       // same as this->x = 6;
		this->x = 5; // explicit use of this->
	}

	void foo() const
	{
		//        x = 7; // Error: *this is constant
	}

	void foo(int x) // parameter x shadows the member with the same name
	{
		this->x = x; // unqualified x refers to the parameter
		// 'this->' required for disambiguation
	}

	int y;
	T(int x) : x(x), // uses parameter x to initialize member x
		y(this->x) // uses member x to initialize member y
	{}

	T& operator= (const T& b)
	{
		x = b.x;
		return *this; // many overloaded operators return *this
	}
};

class Outer {
	//int a[sizeof(*this)]; // error: not inside a member function
	unsigned int sz = sizeof(*this); // OK: in default member initializer
	void f() {
		int b[sizeof(*this)]; // OK
		struct Inner {
			//int c[sizeof(*this)]; // error: not inside a member function of Inner
		};
	}
}

void test_this_pointer1();
void test_this_pointer2();

#endif // FBC_MESSY_TEST_THIS_POINTER_HPP
this_pointer.cpp:

#include "this_pointer.hpp"

Buf::Buf(char* szBuffer, size_t sizeOfBuffer)
{
	sizeOfBuffer++; // account for a NULL terminator

	buffer = new char[sizeOfBuffer];
	if (buffer)
	{
		strcpy_s(buffer, sizeOfBuffer, szBuffer);
		sizeOfBuffer = sizeOfBuffer;
	}
}

Buf& Buf::operator=(const Buf &otherbuf)
{
	if (&otherbuf != this) {
		if (buffer)
			delete[] buffer;

		sizeOfBuffer = strlen(otherbuf.buffer) + 1;
		buffer = new char[sizeOfBuffer];
		strcpy_s(buffer, sizeOfBuffer, otherbuf.buffer);
	}
	return *this;
}

void Buf::Display()
{
	std::cout << buffer << std::endl;
}

void test_this_pointer1()
{
	Box Box1(3.3, 1.2, 1.5);    // Declare box1
	Box Box2(8.5, 6.0, 2.0);    // Declare box2

	if (Box1.compare(Box2)) {
		std::cout << "Box2 is smaller than Box1" << std::endl;
	} else {
		std::cout << "Box2 is equal to or larger than Box1" << std::endl;
	}
}

void test_this_pointer2()
{
	Buf myBuf("my buffer", 10);
	Buf yourBuf("your buffer", 12);

	// Display 'my buffer'
	myBuf.Display();

	// assignment opperator
	myBuf = yourBuf;

	// Display 'your buffer'
	myBuf.Display();
}
函数test_this_pointer1的测试结果如下图:

函数test_this_pointer2的测试结果如下图:


主要参考文献:

1. http://www.tutorialspoint.com/cplusplus/cpp_this_pointer.htm

2. https://msdn.microsoft.com/en-us/library/y0dddwwd.aspx

3. http://en.cppreference.com/w/cpp/language/this


GitHub:https://github.com/fengbingchun/Messy_Test

你可能感兴趣的:(C++中this指针的使用)