判断对象所占内存
class C1 {
private:
int i;
int j;
int k;
};
class C2 {
private:
int i;
int j;
int k;
static int m;
public:
int getK() const { return k; }
void setK(int val) { k = val; }
};
struct S1 {
private:
int i;
int j;
int k;
};
struct S2 {
private:
int i;
int j;
int k;
static int m;
public:
int getK() const { return k; }
void setK(int val) { k = val; }
};
void main() {
cout << "C1:" << sizeof(C1) << endl;
cout << "C2:" << sizeof(C2) << endl;
cout << "S1:" << sizeof(S1) << endl;
cout << "S2:" << sizeof(S2) << endl;
}
C1:12
C2:12
S1:12
S2:12
C++类用C语言实现 内部处理
1 C++中类对象和类成员函数是分开存储的
成员变量:普通成员变量存储于对象中,与struct变量有相同的内存布局和字节对齐方式;静态成员变量存储于全局数据区;
成员函数:存储于代码段中
2 C++类的普通成员函数都包含一个指向当前对象的this指针
3 静态成员函数、成员变量都属于类
4 静态成员函数不包含指向具体对象的指针
5 普通成员函数包含一个指向具体对象的指针
this指针
class Test {
public:
Test(int a, int b) { // --->Test(Test *this, int a, int b)
this->a = a;
this->b = b;
}
void printT() {
cout << "a:" << a << endl;
cout << "b:" << this->b << endl;
}
// const可以写在多个位置
// const 修饰 this 指针所指向的内存空间
/*const*/ void /*const*/ OpVar(int a, int b) const{ //--->void OpVar(const Test const *this, int a, int b)
cout << "b:" << this->b << endl;
}
private:
int a;
int b;
};
void main() {
Test t1(1, 2);
t1.printT(); // printT(&t1)
}
全局函数和成员函数
全局函数和成员函数的转化
class Test {
public:
int a;
int b;
Test(int a = 0, int b = 0) {
this->a = a;
this->b = b;
}
~Test() {
cout << "a:" << a << "\t" << "b:" << b;
cout << "析构函数调用" << endl;
}
// 全局函数变成员函数
Test TestAdd(Test& t2) {
Test tmp(this->a + t2.a, this->b + t2.b);
return tmp;
}
void printT() {
cout << "a:" << a << "\t" << "b:" << b << endl;
}
};
Test TestAdd(Test& t1, Test& t2) {
Test tmp(t1.a + t2.a, t1.b + t2.b);
return tmp;
}
// 成员函数变全局函数
void printT(Test *pT) {
cout << "a:" << pT->a << "\t" << "b:" << pT->b << endl;
}
void main() {
Test t1(1, 2);
Test t2(3, 4);
Test t3;
//全局函数方法
t3 = TestAdd(t1, t2);
printT(&t3);
// 成员变量方法
// 先写测试案例
{
Test t4 = t1.TestAdd(t2); // 匿名对象直接转化为t4
t4.printT();
Test t5;
t5 = t1.TestAdd(t2); // 匿名对象赋值给t5
t5.printT();
}
}
返回引用
class Test {
public:
int a;
int b;
Test(int a = 0, int b = 0) {
this->a = a;
this->b = b;
}
~Test() {
cout << "a:" << a << "\t" << "b:" << b;
cout << "析构函数调用" << endl;
}
// 全局函数变成员函数
Test TestAdd(Test& t2) {
Test tmp(this->a + t2.a, this->b + t2.b);
return tmp;
}
// 返回一个引用 相当于返回自身 返回t1
Test& TestAdd2(Test& t2) {
this->a = this->a + t2.a;
this->b = this->b + t2.b;
return *this;
}
void printT() {
cout << "a:" << a << "\t" << "b:" << b << endl;
}
};
Test TestAdd(Test& t1, Test& t2) {
Test tmp(t1.a + t2.a, t1.b + t2.b);
return tmp;
}
// 成员函数变全局函数
void printT(Test *pT) {
cout << "a:" << pT->a << "\t" << "b:" << pT->b << endl;
}
void main() {
Test t1(1, 2);
Test t2(3, 4);
// t1 = t1 + t2
t1.TestAdd2(t2);
t1.printT();
}
结果
a:4 b:6
a:3 b:4析构函数调用
a:4 b:6析构函数调用