成员变量和成员函数分开存储
#include<iostream>
using namespace std;
class wood {
public:
int num; //非静态成员变量,属于类的对象上
void func() {}//非静态成员函数,不属于类的对象上
static int a;//静态成员变量,共享一份,不属于类的对象上
static void fun() {}//静态成员函数,共享一份,不属于类的对象上
};
int main()
{
wood d;
//空对象占用内存空间:1
//是为了区分空对象占内存的位置
cout << sizeof(d) << endl;
//当有了非静态成员变量num是,占用内存:4
cout << sizeof(d) << endl;
//当再添加一个func函数后,占内存不变,因为成员函数和成员函数分开存储
cout << sizeof(d) << endl;
//静态成员变量不是内对象,不算类对象内存大小
cout << sizeof(d) << endl;
system("pause");
return 0;
}this指针 this指针指向被调用的成员函数所属的对象 this指针是隐含每一个非静态成员函数类的指针 this指针无需定义可直接使用 用途: 1.当形参和成员变量相同时,可用this进行区分 2.在类的非静态成员中返回对象本身,可用return this
#include<iostream>
using namespace std;
class wood {
public:
int num;
wood(int NUM):num(NUM){}
wood& addNum(wood &w1)
{
this->num += w1.num; //num不为共享,一个是对象w1的num,一个是w2的num
//this指向w2的指针,而*this指向的就是w2这个对象本体
return *this;
}
};
int main()
{
wood w1(10);
wood w2(10);
//链式编程
w2.addNum(w1).addNum(w1);
cout << w2.num << endl;
system("pause");
return 0;
}