前言
类和对象第一部分知识包括定义访问限定符类域实例化this指针
本人其他文章:恋风诗
文章中的源码[gitte]:mozhengy
类和对象(一)
-
- 前言
- [1. 类的定义](#1. 类的定义)
-
- 引例
- [1.1 类定义格式](#1.1 类定义格式)
- [1.2 类的访问限定符](#1.2 类的访问限定符)
- [1.3 类域](#1.3 类域)
- [2. 实例化](#2. 实例化)
-
- [2.1 实例化概念](#2.1 实例化概念)
- [2.2 对象大小](#2.2 对象大小)
- [3. this指针](#3. this指针)
- 4.C++和C语言实现Stack对比
- 总结
1. 类的定义
引例
C语言中我们学习了结构体struct,struct中可以定义变量,如之前学的数据结构栈的定义
c
typedef struct Stack
{
int *a;
int top;
int capacity;
}Stack;
在C++中,我们将结构体进一步升级,进一步拓展结构体的内容,不仅可以定义变量,还可以定义函数
cpp
struct Stack
{
void Init()
{
a = (int*)malloc(sizeof(int) * 4);
if (a == nullptr)
{
perror("malloc error");
return;
}
top = 0;
capacity = 4;
}
int* a;
int top;
int capacity;
};
此时
在C++中,结构体的类型可以是struct Stack,也认可用Stack表示
同样定义结构体变量可以直接表示为
Stack st1;
。
在C++中,类是类似struct的事物,类则是用class定义
1.1 类定义格式
class为定义类的关键字,Stack为类的名字,{}中为类的主体。
- 类定义结束时后面分号不能省略。
- 类体中内容称为类的成员:类中的变量称为类的属性或成员变量; 类中的函数称为类的方法或者成员函数。
- 这里的public和private称为类的访问限定符,(后文会详解)
- 类的类型就是名字classname
cpp
class classname
{
public:
//成员函数
int add(int a, int b)
{
return a + b;
}
private:
//成员变量
int a;
int b;
};
定义的两种方法
1.声明与定义不分离
定义在类面的成员函数默认为inline。 声明和定义全部放在类体中,在类体中定义成员函数,
cpp
class Stack
{
public:
void Init()
{
//省略
}
private:
int* a;
int top;
int capacity;
};
2.声明定义分离
这里会牵扯到新的知识------类域
- 之前了解过C++的常见域中的全局域、局部域、命名空间域,类域是新的一种
- 在类体外定义成员函数,需要使用类域名字加::加成员函数名字来指明函数属于哪一个类域,进而才能在类域外部定义成员函数
- 类域影响的是编译的查找规则,下面程序中Init如果不指定类域Stack,那么编译器就把Init当成全 局函数,那么编译时,找不到array等成员的声明/定义在哪里,就会报错。指定类域Stack,就是知 道Init是成员函数,当前域找不到的array等成员,就会到类域中去查找。
cpp
#include<iostream>
using namespace std;
class Stack
{
public:
// 成员函数
void Init(int n = 4);
private:
// 成员变量
int* array;
size_t capacity;
size_t top;
};
// 声明和定义分离,需要指定类域
void Stack::Init(int n)
{
array = (int*)malloc(sizeof(int) * n);
if (nullptr == array)
{
perror("malloc申请空间失败");
return;
}
capacity = n;
top = 0;
}
int main()
{
Stack st;
st.Init();
return 0;
}
- 有时我们命名的变量会和函数的形参冲突,因此为了区分成员变量,一般习惯上成员变量会加一个特殊标识,如成员变量前面或者后面加_ 或者 m 开头,注意C++中这个并不是强制的,只是一些惯例,具体看学校和公司的要求。
cpp
class Date
{
public:
void Init(int year = 1, int month = 1, int day = 1)
{
_year = year;
_month = month;
_day = day;
}
private:
int _day;
int _month;
int _year;
};
1.2 类的访问限定符
• C++一种实现封装的方式,用类将对象的属性与方法结合在一块,让对象更加完善,通过访问权限 选择性的将其接口提供给外部的用户使用。
具体如下
类的访问限定符 public 公开 private 私有 protected 保护 访问权限 类内/类外均可访问 访问权限 仅类内可访问 访问权限 类内可访问 其他规则 默认访问权限 class 默认 private struct 默认 public
由于继承等内容未学习,后续会补充
• 访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现时为止,如果后面没有 访问限定符,作用域就到 }即类结束。
• 一般成员变量都会被限制为private/protected,需要给别人使用的成员函数会放为public。
1.3 类域
上面提到过,下面再说一下
类定义了一个新的作用域,类的所有成员都在类的作用域中,在类体外定义成员时,需要使用 :: 作 用域操作符指明成员属于哪个类域。
• 类域影响的是编译的查找规则,下面程序中Init如果不指定类域Stack,那么编译器就把Init当成全 局函数,那么编译时,找不到array等成员的声明/定义在哪里,就会报错。指定类域Stack,就是知 道Init是成员函数,当前域找不到的array等成员,就会到类域中去查找。
cpp
#include<iostream>
using namespace std;
class Stack
{
public:
// 成员函数
void Init(int n = 4);
private:
// 成员变量
int* array;
size_t capacity;
size_t top;
};
// 声明和定义分离,需要指定类域
void Stack::Init(int n)
{
array = (int*)malloc(sizeof(int) * n);
if (nullptr == array)
{
perror("malloc申请空间失败");
return;
}
capacity = n;
top = 0;
}
int main()
{
Stack st;
st.Init();
return 0;
}
2. 实例化
2.1 实例化概念
-
用类类型在物理内存中创建对象的过程,称为类实例化出对象。
-
类是对象进行一种抽象描述,是一个模型一样的东西,限定了类有哪些成员变量,这些成员变量只 是声明,没有分配空间,用类实例化出对象时,才会分配空间。
-
一个类可以实例化出多个对象,实例化出的对象 占用实际的物理空间,存储类成员变量。打个比方:类实例化出对象就像现实中使用建筑设计图建造出房子,类就像是设计图,设计图规划了有多 少个房间,房间大小功能等,但是并没有实体的建筑存在,也不能住人,用设计图修建出房子,房子才能住人。
-
同样类就像设计图一样,不能存储数据,实例化出的对象分配物理内存存储数据。
-
一个类可以实例化处多个对象,实例化出的对象分配实际的物理空间去存储成员变量
下面是实例化的例子
cpp
#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, d2;
d1.Init(2024, 3, 31);
d1.Print();
d2.Init(2024, 7, 5);
d2.Print();
return 0;
}
但在这个例子中我们将private屏蔽掉,即默认访问成员变量的权限变为public,但是你仍然不可以使用域访问限定符::去访问类中的成员变量,因为类并没有实际分配内存空间去存储成员变量,按照上面的例子,你拿出一张房子的设计图,不是把房子举起来
cpp
//这种写法是错误的!!!!!!
#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::_day;
return 0;
}
会有以下报错
2.2 对象大小
类实例化出的每个对象,都有独立的数据空间,所以对象中肯定包含 成员变量,那么成员函数是否包含呢?首先函数被编译后是一段指令,对象中没办法存储,这些指令 存储在一个单独的区域(代码段),那么对象中非要存储的话,只能是成员函数的指针。
对象中是否有存储指针的必要呢,Date实例化d1和d2两个对象,d1和d2都有各自独立的成员变量 _year/_month/_day存储各自的数据,但是d1和d2的成员函数Init/Print指针却是一样的,存储在对象 中就浪费了。
如果用Date实例化100个对象,那么成员函数指针就重复存储100次,太浪费了。
C++规定类实例化的对象也要符合内存对齐的规则。
内存对齐规则
- 第一个成员在与结构体偏移量为0的地址处。
- 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。
- 注意:对齐数 = 编译器默认的一个对齐数 与 该成员大小的较小值。
- VS中默认的对齐数为8
- 结构体总大小为:最大对齐数(所有变量类型最大者与默认对齐参数取最小)的整数倍。
- 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小 就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。
- 对于有一个至多个成员函数的类对象的计算规则同结构体的内存对齐计算规则,
- 对于一个都没有成员函数的类对象,编译器默认为它分配1字节的空间,这是为了占位,并不存储有效数据,确保由它实例化出的对象存在
cpp
#include<iostream>
using namespace std;
// 计算⼀下A/B/C实例化的对象是多⼤?
class A
{
public:
void Print()
{
cout << _ch << endl;
}
private:
char _ch;
int _i;
};
class B
{
public:
void Print()
{
//...
}
};
class C
{
};
int main()
{
A a;
B b;
C c;
cout << sizeof(a) << endl;
cout << sizeof(b) << endl;
cout << sizeof(c) << endl;
return 0;
}
3. this指针
- Date类中有 Init 与 Print 两个成员函数,函数体中没有关于不同对象的区分,那当d1调用Init和 Print函数时,该函数是如何知道应该访问的是d1对象还是d2对象呢?那么这里就要看到C++给了 一个隐含的this指针解决这里的问题
- 编译器编译后,类的成员函数默认都会在形参第一个位置,增加一个当前类类型的指针,叫做this 指针。比如Date类的Init的真实原型为,
void Init(Date* const this, int year, int month, int day)
- 类的成员函数中访问成员变量,本质都是通过this指针访问的,如Init函数中给_year赋值
,this->_year = year;
- C++规定不能在实参和形参的位置显示的写this指针(编译时编译器会报错),但是可以在函数体内显 示使用this指针。
cpp
#include<iostream>
using namespace std;
class Date
{
public:
// void Init(Date* const this, int year, int month, int day)
void Init(int year, int month, int day)
{
// 编译报错:error C2106: "=": 左操作数必须为左值
// this = nullptr;
// this->_year = year;
_year = year;
this->_month = month;
this->_day = day;
}
void Print()
{
cout << _year << "/" << _month << "/" << _day << endl;
}
private:
// 这里只是声明,没有开空间
int _year;
int _month;
int _day;
};
int main()
{
// Date类实例化出对象d1和d2
Date d1;
Date d2;
// d1.Init(&d1, 2024, 3, 31);
d1.Init(2024, 3, 31);
d1.Print();
d2.Init(2024, 7, 5);
d2.Print();
return 0;
}
4.C++和C语言实现Stack对比
面向对象三大特性:封装、继承、多态,下面的对比我们可以初步了解一下封装。
通过下面两份代码对比,我们发现C++实现Stack形态上还是发生了挺多的变化,底层和逻辑上没啥变 化。
C++中数据和函数都放到了类里面,通过访问限定符进行了限制,不能再随意通过对象直接修改数 据,这是C++封装的一种体现,这个是最重要的变化。这里的封装的本质是一种更严格规范的管 理,避免出现乱访问修改的问题。当然封装不仅仅是这样的,我们后面还需要不断的去学习。 C++中有一些相对方便的语法,比如Init给的缺省参数会方便很多,成员函数每次不需要传对象地 址,因为this指针隐含的传递了,方便了很多,使用类型不再需要typedef用类名就很方便
C实现Stack代码
cpp
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)
{
assert(ps);
// 满了, 扩容
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
int main()
{
ST s;
STInit(&s);
STPush(&s, 1);
STPush(&s, 2);
STPush(&s, 3);
STPush(&s, 4);
while (!STEmpty(&s))
{
printf("%d\n", STTop(&s));
STPop(&s);
}
STDestroy(&s);
return 0;
}
C++实现Stack代码
cpp
#include<iostream>
using namespace std;
typedef int STDataType;
class Stack
{
public:
// 成员函数
void Init(int n = 4)
{
_a = (STDataType*)malloc(sizeof(STDataType) * n);
if (nullptr == _a)
{
perror("malloc申请空间失败");
return;
}
_capacity = n;
_top = 0;
}
void Push(STDataType x)
{
if (_top == _capacity)
{
int newcapacity = _capacity * 2;
STDataType* tmp = (STDataType*)realloc(_a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
_a = tmp;
_capacity = newcapacity;
}
_a[_top++] = x;
}
void Pop()
{
assert(_top > 0);
--_top;
}
bool Empty()
{
return _top == 0;
}
int Top()
{
assert(_top > 0);
return _a[_top - 1];
}
void Destroy()
{
free(_a);
_a = nullptr;
_top = _capacity = 0;
}
private:
// 成员变量
STDataType* _a;
size_t _capacity;
size_t _top;
};
int main()
{
Stack s;
s.Init();
s.Push(1);
s.Push(2);
s.Push(3);
s.Push(4);
while (!s.Empty())
{
printf("%d\n", s.Top());
s.Pop();
}
s.Destroy();
return 0;
}
总结
内容虽然冗余,无奈想做的详细,因为C++已经有点困难了,同时本文尝试用mermaid画思维导图,如果感觉挺好以后继续用,若有错误还望多多指正。