面向不存在的东西
OOP(面向对象【找不到对象的☞🤣】)
1.类 (累)
- 定义:可以用struct和class定义
struct 类{
int 年龄 =114514;//成员变量
void 成员函数(方法){
方法要干嘛
}
};
class 类{
int 年龄 =114514;//成员变量
void 成员函数(方法){
方法要干嘛
}
};
2.怎么用这个类
class test {
public:
int mAge;
int func() {
std::cout << "shit";
return age;
}
};
int main() {
//利用类创建对象
//类名 变量名;
test hahaha;
//也可以使用 指针
test *pTest = &hahaha ;
hahaha.age = 10086;
hahaha.func();
return 0;
}
这些创建的对象,指针的内存都是在函数的栈空间,自动分配和回收
3.struct和class的区别是什么
- struct默认成员权限是public,而class默认权限是private
- 私有和公有的区别私有只允许类内访问
对象内存布局🙄
先看以下代码
#include <iostream>
using namespace std;
struct cup {//可以是class 也可以是struct 因为我们在类内定义了public和private
public://公共权限,类外可以直接访问使用
int price;
int value;
int height;
void inputWater() {
cout << "water ins comming!" << endl;
}
void setHotWater(int v1) {
hotWater = v1;
}
int getHotWater() {
return hotWater;
}
private://私有权限,类外不可以直接访问使用,但可以通过public范围内的成员函数方法来简介修改访问
int hotWater;
};
int main() {
cup newCup;
cup newCup2;
cup* ptr = &(newCup);
ptr->setHotWater(33);
cout << ptr->getHotWater() << endl;
cout << &ptr->price << endl;
cout << &ptr->value << endl;
cout << &ptr->height << endl;
cout << sizeof(newCup) << endl;//我们看看当前的杯子占用了多少内存空间
getchar();
}
执行完之后会显示这几个变量其实空间是连续的
我们的内存其实可以分成四个区
分别是
| 栈空间 | 堆空间 | 代码区 | 全局区 |
|---|---|---|---|
| 由计算机控制回收 | 玩家手动控制回收(delete) | 存放函数的位置(只读) | 全局变量等 |
| 我们建立的对象,是存储在栈空间,而方法(类中的函数)则是存在于代码区 |
那么问题来了->代码区如何访问存在栈空间的
做个假设
#include <iostream>
using namespace std;
class car {
public:
int price=2333;
void run(car* car1) {
cout << car1->price << "车跑起来了" << endl;
}
};
int main() {
car car1;
car1.run(&car1);//将car1的地址传进去
return 0;
}
我们做一下梳理
1.先调用car1.run
2.传递一个地址(&car1)过去,这个地址是创建的对象car1的地址(好,现在run函数知道car到底是哪个car,并且知道他家住在哪里了)
3.run函数知道应该用哪个参数了,然后启动!
this 指针
this是个指针,在我们调用成员变量时
car car1;
car1.run();
它偷偷传地址了,传给了run()函数里
而run()函数里有一个this指针 相当于 this = &car1;
我们可以通过打印输出看看是否相同
#include <iostream>
using namespace std;
class car {
public:
int price=2333;
void run(car* car1) {
cout<<this<<"<-this"<<endl;
// cout << car1->price << "车跑起来了" << endl;
}
};
int main() {
car car1;
car1.run(&car1);//将car1的地址传进去
cout <<&car1<<"<-car1"<<endl;
return 0;
}
通过实验我们得到,他俩的地址相同;这种就是一个隐式参数
this指针存储着函数调用者的地址 this 指向函数调用者
举个栗子
#include <iostream>
using namespace std;
class ha {
public:
int c = 1;
int func() {
cout << "哈哈哈" << this->c << endl;;
return 0;
}
};
int main() {
ha ha1;
ha1.c = 12138;
ha ha2;
ha2.c = 114514;
ha1.func();
ha2.func();
return 0;
}
明显有个取地址的过程
ha1.func();
lea rcx,[ha1]
call ha::func (07FF7427314FBh)
ha2.func();
lea rcx,[ha2]
call ha::func (07FF7427314FBh)
这取出的就是我们创建的对象的地址
<提一嘴>
-因为vs编译器会把 栈空间填充CC 因为CC的机器码是int3 int3起到一个断点的作用。
如果指向了错误的地址 程序会停止保证安全
封装
- 概念:成员变量私有化,提供公共的Get和Set方法去给外界使用
- 意义,保证操作安全,接受数据合法

浙公网安备 33010602011771号