this指针特性
- this指针的类型:类类型* const,即成员函数中,不能给this指针赋值。
- 只能在“成员函数”的内部使用
- this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给 this形参。所以对象中不存储this指针。
- this指针是“成员函数”第一个隐含的指针形参,一般情况由编译器通过ecx寄存器自动传 递,不需要用户传递
1、下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class AA { public: void Print() { cout << "Print(AA)" << endl; } private: int _a; }; void test_this1() { AA* p = nullptr; p->Print(); }
虽然在函数
test_this1
中创建了一个指向AA
类型的空指针p
,但在调用p->Print()
之前并没有对指针进行解引用操作。由于Print()
函数内部没有使用成员变量_a
,所以在调用Print()
函数时,空指针p
并不会引发运行时错误。因此,程序将正常运行(选项 C)。
2、下面程序编译运行结果是? A、编译报错 B、运行崩溃 C、正常运行
class BB { public: void PrintB() { cout << _b << endl; } private: int _b; }; void test_this2() { BB* p = nullptr; p->PrintB(); }
当调用
p->PrintB()
时,会尝试访问成员变量_b
,但由于p
是空指针,因此会导致运行时错误。因为空指针无法访问对象的成员变量。