C++基础复习提升-this那些事
参考C++那些事-光程大佬的网站
上一篇C++基础复习提升-static那些事
下一篇C++基础复习提升-inline那些事
(1) 一个对象的this指针并不是对象本身的一部分(与python中的self异曲同工),不会影响sizeof(对象)
的结果。
(2) this作用域是在类内部,当在类的非静态成员函数中访问类的非静态成员的时候,编译器会自动将对象本身的地址作为一个隐含参数传递给函数。所以this指向的其实就是传入的对象地址,它作为非静态成员函数的隐含形参,对各成员的访问均通过this进行。而静态成员程序为它们在静态存储中单独分配了空间,它们没有this指针。注意静态成员函数不能使用const修饰为常静态成员函数,因为声明一个非静态成员函数为const时,this指针相当于类名 const,而静态成员函数没有this指针。
常函数写法:void func() const;,const修饰函数返回值的写法:const void func();静态函数可以用后者来构建,但是无法使用前者构建。
(3) 在类的非静态成员函数中返回类对象本身,直接使用return *this;
(4) 当参数与成员变量名相同时,正确写法:this->n=n;错误写法n=n;
#include <iostream>
#include <cstring>
using namespace std;
class Person {
public:
// 枚举类型enum
typedef enum {
BOY = 0,
GIRL,
} SexType;
Person(char *n, int a, SexType s) {
// strlen获取字符数组的长度
this->name = new char[strlen(n) + 1];
// strcpy将n的内容复制到name
strcpy(name, n);
this->age = a;
this->sex = s;
}
// 使用常函数,提高程序的健壮性,this指向const Person *const
int get_age() const {
return this->age;
}
// 对象初始化时调用
static const SexType get_enum() {
return GIRL;
}
// 返回sex值
SexType get_sex() const { return this->sex; }
// 隐式传入this指针,this指向Person *const
Person &add_age(int a) {
// 调用该对象时,对该对象的age重新赋值
this->age += a;
// 返回对象本身
return *this;
}
~Person() {
// 释放掉堆内存的对象
delete[] name;
}
private:
char *name;
int age;
SexType sex;
};
int main() {
Person p("zhangsan", 20, Person::get_enum());
// age:20
cout << p.get_age() << endl;
// age:30
cout << p.add_age(10).get_age() << endl;
// sex:1
cout << p.get_sex() << endl;
return 0;
}