当前位置:网站首页>Classes and Objects: Above
Classes and Objects: Above
2022-08-01 00:03:00 【Lazy -】
面向过程和面向对象初步认识
- C语言是面向过程的,关注的是过程,分析出求解问题的步骤,通过函数调用逐步解决问题
- C++是基于面向对象的,关注的是对象,将一件事情拆分成不同的对象,靠对象之间的交互完成

类的引入
#include<iostream>
using namespace std;
//C
struct Stack_C
{
int* a;
int top;
int capacity;
};
//C++
struct Stack_CPP
{
void Init()
{
a = 0;
top = capacity = 0;
}
void Push(int x)
{
// ...
}
void Pop()
{
// ...
}
int* a;
int top;
int capacity;
};
int main()
{
struct Stack_C st1;
//Stack是类名,也是一种类型,直接用就行了
Stack_CPP st2;
st2.Init();
st2.Push(1);
st2.Push(2);
st2.Push(3);
return 0;
}
- 在C语言中struct中只能定义成员变量
- 在C++中引入了类的概念,struct中不仅仅可以定义成员变量,还可以定义成员函数
类的定义
实现一
#include<iostream>
using namespace std;
class Person
{
//显示基本信息
void Show_information() {
cout << _name << _age << _area << endl;
}
char* _name;
char* _area;
int _age;
};
int main()
{
Person zhansan;
return 0;
}- 声明和定义全部放在类体中,需注意:成员函数如果在类中定义,编译器可能会将其当成内联函数处理.
实现二

- 类声明放在.h文件中,成员函数定义放在.cpp文件中,
- 注意:成员函数名前需要加类名::
Supplementary description of the class definition
- 小函数,想成为inline,You can define it directly in the class
- 如果是大函数,应该声明和定义分离
类的访问限定符及封装

#include<iostream>
using namespace std;
class Stack
{
public:
void Init()
{
a = 0;
top = capacity = 0;
}
void Push(int x)
{
// ...
}
void Pop()
{
// ...
}
int Top()
{
return a[top - 1];
}
private:
//protected:
int* a;
int top;
int capacity;
};
int main()
{
Stack st;
st.Init();
st.Push(1);
st.Push(2);
st.Push(3);
//cout << st.a[st.top] << endl;
//cout << st.a[st.top-1] << endl;
cout << st.Top() << endl;
//st.a = nullptr;
return 0;
}- public修饰的成员在类外可以直接被访问
- protected和private修饰的成员在Outside the class cannot be accessed directly(此处protected和private是类似的)
- 访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止
- 如果后面没有访问限定符,作用域就到 } 即类结束.
- class的默认访问权限为private,struct为public(因为struct要兼容C)
C++中struct和class的区别是什么?
- C++需要兼容C语言,所以C++中struct可以当成结构体使用.另外C++中struct还可以用来定义类.和class定义类是一样的,区别是struct定义的类默认访问权限是public,class定义的类默认访问权限是private
封装
举个例子:Get the top of the stack

- C语言->There is no way to encapsulate,For users herest.topMay be the top element of the stack,It may also be the last element at the top of the stack,可以直接访问数据,但是不规范
- C++ -> 封装 必须规范使用函数访问数据,不能直接访问数据,
类的实例化
类不占用空间,The class happens when it is used实例化,Just opened up space


- When using classes properly,是需要Declaration and definition are separated,Open up a space called definition,A statement that does not open up space is called a statement
- static A decorated statement,只在当前文件可见,The symbol table is not put in when linking,So the addresses printed twice are different
- extern A decorated statement,It is put into the symbol table at link time,So the address printed twice is the same
- 注意:.h文件会在.cpp中展开,所以在.hThere are no variables declared in the file, only variables are defined,就会出现链接错误,重定义,
类对象模型
类对象的存储方式猜测
猜测一:对象中包含类的各个成员

- 缺陷:每个对象中成员变量是不同的,都调用同一份函数,It is saved once every time the same code is called,multiple objects,相同代码保存多次,浪费空间.
猜测二:代码只保存一份,在对象中保存存放代码的地址

- This is when accessing class member functions,is passed in the objectA pointer to the class member function table is reserved,Accessed by dereferencing a pointer,
猜测三:只保存成员变量,成员函数存放在公共的代码段


- Compile and link according toThe function name goes to the public code area to find the function address
- C++Class objects are stored in a third way,只保存成员变量,成员函数存放在公共的代码段
#include<iostream>
using namespace std;
class A1
{
public:
void PrintA()
{
cout << _a << endl;
}
void func()
{
cout << "void A::func()" << endl;
}
private:
char _a;
int _i;
};
class A2 {
public:
void f2() {}
};
class A3{
};
int main()
{
cout << sizeof(A1) << endl;
cout << sizeof(A2) << endl;
cout << sizeof(A3) << endl;
return 0;
}
- 一个类的大小,实际就是该类中”成员变量”之和,这里和CThe same happens with language内存对齐
- 注意:空类的大小,空类比较特殊,编译器给了空类一个字节to uniquely identify objects of this class.
Recommendations for member variable naming conventions
驼峰法——单词和单词之间首字母大写间隔
class Date
{
public:
void Init(int year)
{
_year = year;
}
private:
int _year;
};- 函数名、类名etc. Capitalize the first letter of all words DateMgr
- 变量首字母小写,后面单词首字母大写 dateMgr
- 成员变量,Add before the first word_ _dateMgr
this指针
#include<iostream>
using namespace std;
class Date
{
public:
void Init(int year, int month, int day)
{
_year = year;
_month = month;
_day = day;
}
void Print()
{
cout << _year << "-" << _month << "-" << _day << endl;
}
private:
int _year; // 年 -> 声明
int _month; // 月
int _day; // 日
};
int main()
{
Date d1;
d1.Init(2022, 7, 17);
Date d2;
d2.Init(2022, 7, 18);
d1.Print();
d2.Print();
return 0;
}- Date类中有 Init与Print 两个成员函数,They are all placed公共代码区中的,There is no distinction between different objects in the function body,那当d1调用 Init 函数时,lnitHow does this function know that it should be rightd1进行初始化,而不是给d2进行初始化
- C++中通过引入this指针解决该问题,即:
- C++编译器给每个“非静态的成员函数“增加了一个隐藏的指针参数,
- 让该指针指向当前对象(函数运行时调用该函数的对象),在函数体中所有“成员变量”的操作,都是通过该指针去访问.
- 只不过所有的操作对用户是透明的,即用户不需要来传递,编译器自动完成.
#include<iostream>
using namespace std;
class Date
{
public:
void Init(Date* const this, int year, int month, int day)
{
this->_year = year;
this->_month = month;
this->_day = day;
}
void Print(Date* const this)
{
cout << this->_year << "-" << this->_month << "-" << this->_day << endl;
}
private:
int _year; // 年 -> 声明
int _month; // 月
int _day; // 日
};
int main()
{
Date d1;
d1.Init(&d1,2022, 7, 17);
Date d2;
d2.Init(&d2,2022, 7, 18);
d1.Print();
d2.Print();
return 0;
}- Here I hide the compilerthisThe pointer is displayed,But the compiler will report an error,
- 注意:实参和形参位置Delivery and reception cannot be displayedthis指针,但是可以在成员函数内部使用this指针
this指针的特性
- this指针的类型:类类型* const,即成员函数中,不能给this指针赋值.
- 只能在“成员函数”的内部使用
- this指针本质上是“成员函数”的形参,当对象调用成员函数时,将对象地址作为实参传递给this形参.所以对象中不存储this指针.
- this指针是“成员函数”第一个隐含的指针形参,vsThe following pass is passedecx寄存器传递的,这样thisEfficiency can be improved when accessing variables,But these optimizations取决于编译器,
关于this指针的存储位置
- 栈区,因为他是一个形参
用thispointer proof类对象的存储方式
#include<iostream>
using namespace std;
class A
{
public:
void Print()
{
cout << "Print()" << endl;
//cout << this << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print(); //正常运行
return 0;
}
- This code does not crash,Compilation error,它是会正常运行的
- p->Print如果对p进行了解引用,就会报错,But here is normal operation,可见How class objects are stored is guesswork three:只保存成员变量,成员函数存放在公共的代码段
#include<iostream>
using namespace std;
class A
{
public:
void Print(int x)
{
this->_a = x;
cout << this->_a << endl;
}
private:
int _a;
};
int main()
{
A* p = nullptr;
p->Print(1); //崩溃
/*A m;
m.Print(1);*/
return 0;
}- This code will crash,Null pointers are fine,但是对There will be a problem with null pointers for indirect references
边栏推荐
- Mysql environment installation under Linux (centos)
- Recommendation system: Summary of common evaluation indicators [accuracy rate, precision rate, recall rate, hit rate, (normalized depreciation cumulative gain) NDCG, mean reciprocal ranking (MRR), ROC
- 消息队列存储消息数据的MySQL表格
- vim的基本使用-底行模式
- 如何设计高可用高性能中间件 - 作业
- C# Rectangle basic usage and picture cutting
- 【FPGA教程案例43】图像案例3——通过verilog实现图像sobel边缘提取,通过MATLAB进行辅助验证
- IPD process terminology
- Xinao Learning Plan The Road to Informatics Competition (2022.07.31)
- 手写一个简单的web服务器(B/S架构)
猜你喜欢

NIO编程
Mysql environment installation under Linux (centos)

Network security - crack WiFi through handshake packets (detailed tutorial)

游戏安全03:缓冲区溢出攻击简单解释
![[Reading Notes -> Data Analysis] 02 Data Analysis Preparation](/img/e7/258daf851746cb043f301437ee3bbe.png)
[Reading Notes -> Data Analysis] 02 Data Analysis Preparation

MLP神经网络,GRNN神经网络,SVM神经网络以及深度学习神经网络对比识别人体健康非健康数据

网络安全--通过握手包破解WiFi(详细教程)

How to reduce the gap between software design and implementation

/etc/sysconfig/network-scripts 配置网卡

Kyoto University:Masaki Waga | 黑箱环境中强化学习的动态屏蔽
随机推荐
如何设计高可用高性能中间件 - 作业
Weekly Summary
SQL injection Less54 (limited number of SQL injection + union injection)
Flutter教程之四年开发经验的高手给的建议
SQL injection Less47 (error injection) and Less49 (time blind injection)
【读书笔记->数据分析】02 数据分析准备
网络安全--通过握手包破解WiFi(详细教程)
To help the construction of digital government, the three parties of China Science and Technology build a domain name security system
Difference between first and take(1) operators in NgRx
消息队列存储消息数据的MySQL表格
Program processes and threads (concurrency and parallelism of threads) and basic creation and use of threads
SQL injection Less46 (injection after order by + rand() Boolean blind injection)
Google Earth Engine——Error: Image.clipToBoundsAndScale, argument ‘input‘: Invalid type的错误解决
vector的基本实现
IJCAI2022 | 代数和逻辑约束的混合概率推理
高等代数_证明_任何矩阵都相似于一个上三角矩阵
Web API 介绍和类型
嵌入式开发没有激情了,正常吗?
SQL注入 Less42(POST型堆叠注入)
How to Design High Availability and High Performance Middleware - Homework