一、this的定义
this指针是存在于类的成员函数中,指向被调用函数所在的类实例的地址。一个对象的this指针并不是对象本身的一部分,也就意味着并不会影响sizeof的结果。
二、this的作用
保存当前对象的地址,是一个常量指针,不允许改变this的值
三、为什么使用this指针
-
在类的非静态成员函数中返回类对象本身的时候,直接使用 return *this;
-
当参数与成员变量名相同时,如this->n = n (不能写成n = n)。
四、this指针为空(nullptr对象为什么可以调用函数)
this指针为空,即当前的对象为nullptr,如果编译器报错this为空,请检查当前的对象是否空。
this指针为空即一个nullptr对象,不能调用含有非静态成员的函数(只能调用不使用this指针的函数)。
对象调用非静态成员函数时,编译器会默认把this指针作为第一个参数!即void func(args) = void func(this,args)
点击查看代码
#include <iostream>
using namespace std;
class test
{
public:
static void f1() { cout << y << endl; }
void f2() { cout << y << endl; } // void f2(test* t){cout << y << endl;} 因为y是静态的,所以不需要使用this指针
void f3() { cout << x << endl; } // 相当于 cout<< this->x <<endl;
void f4(int p) { cout << p << endl; }
void f5() { cout << 5 << endl; }
int f6() { return 6; }
//static void f7() { cout << x << endl; } //静态函数不能调用非静态成员变量
int x;
static int y;
};
int test::y = 1;
int main()
{
test* p = nullptr;
p->f1();
p->f2(); // p->f2(p); p在f2函数体内并不使用,所以正确
//p->f3(); //cout << nullptr->x << endl; 错误
p->f4(5);
p->f5();
p->f6();
getchar();
return 0;
}
点击查看代码
nullptr不能调用virtual函数,子类自己的函数只要不访问非静态成员仍然可以调用
#include <iostream>
class A
{
public:
virtual void Func()
{
std::cout << "a\n";
}
};
class B :
public A
{
public:
void FuncB()
{
std::cout << "b\n";
}
};
int main()
{
B* b = nullptr;
//b->Func(); // 抛出异常,因为b是nullptr没有虚表
b->FuncB(); //正确
}