成员变量和成员函数分开储存
空函数
#include <iostream>
using namespace std;
class Person {
public:
//int old;
Person() {
cout << "默认无参" << endl;
}
};
void test(){
Person p;
cout<<sizeof(p)<<endl;//编译器为空对象占用分配1字节,为了区分空对象占内存的位置
}
int main() {
test();
return 0;
}
非空函数
#include <iostream>
using namespace std;
class Person {
public:
int old;//非静态成员变量,内存属于类对象
static int ed;//静态成员变量,内存不属于类对象
//非静态成员函数,内存不属于类对象
void funk(){
cout<< 67 << endl;
}
//静态成员函数,内存属于类对象
static void runk(){
}
Person() {
cout << "默认无参" << endl;
}
~Person(){
cout<< "析构" <<endl;
}
};
void test(){
Person p;
cout<<sizeof(p)<<endl;
}
int main() {
test();
return 0;
}
this
this概念
this是c++提供的特殊对象指针
this指向被调用的成员函数所指的对象
this指针隐含在每一个非静态成员函数内,不需要我们再去定义
this用途
当形参和成员变量同名时,可以用this指针来区分
Person(int old){
old = old;
}
Person(int old){
this->old = old;
}
在类的非静态成员函数中返回对象本身,可用return*this
#include <iostream>
using namespace std;
class Person {
public:
int old;
Person() {
cout << "默认无参" << endl;
}
Person(int old){
old = old;
}
~Person(){
cout<< "析构" <<endl;
}
Person& Add(Person &p){
this->old+=p.old;
return *this;
}
};
void test(){
Person p(10);
Person p1(5);
p.Add(p1).Add(p1);//链式编程
cout<<sizeof(p)<<endl;
}
int main() {
test();
return 0;
}