首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >【C++】类和对象(上)

【C++】类和对象(上)

作者头像
云边有个稻草人
发布2024-10-21 20:08:25
发布2024-10-21 20:08:25
1960
举报

1. 类的定义

1.1 类定义格式

  • class为定义类的关键字,Stack为类的名字,{}中为类的主体,注意类定义结束时后面分号不能省略。类体中内容称为类的成员:类中的变量称为类的属性或成员变量;类中的函数称为类的方法或者成员函数。
  • 为了区分成员变量,一般习惯上成员变量会加一个特殊标识,如成员变量前面或者后面加_或者m开头,注意C++中这个并不是强制的,只是一些惯例,具体看公司的要求。
  • C++中struct也可以定义类,C++兼容C中struct的用法,同时struct升级成了类,明显的变化是struct中可以定义函数,一般情况下我们还是推荐使用class定义类。
  • 定义在类里面的成员函数默认为inline。
代码语言:javascript
复制
#include<iostream>
#include<assert.h>

using namespace std;
class Stack
{
public:
	void Init(int n = 4)
	{
		array = (int*)malloc(sizeof(int) * n);
		if (array == nullptr)
		{
			perror("malloc申请空间失败");
			return;
		}
		capacity = n;
		top = 0;
	}

	void Push(int x)
	{
		//...扩容
		array[top++] = x;
	}

	int Top()
	{
		assert(top > 0);
		return array[top - 1];
	}

	void Destroy()
	{
		free(array);
		array = nullptr;
		top = capacity = 0;
	}

private:
		int* array;
		size_t capacity;
		size_t top;
};

//C++兼容C语言中的struct,同时struct也升级成了类
struct Person
{
public:
	void Init(const char* name, int age, int tel)
	{
		strcpy(_name, name);
		_age = age;
		_tel = _tel;
	}

	void Print()
	{
		cout << "姓名:" << _name << endl;
		cout << "年龄:" << _age << endl;
		cout << "电话:" << _tel << endl;
	}

private:
	char _name[10];
	int _age;
	int _tel;
	//...
};

typedef struct QueueNode
{
	struct QueueNode* next;
	int val;
}QNode;

typedef struct Queue
{
	Queue* head;
	Queue* tail;
	int size;
}QU;

void QueueInit(QU* q)
{
	q->head = nullptr;
	q->tail = nullptr;
	q->size = 0;
}

int main()
{
	//类名就是类型,用类型定义对象
	Stack st;

	st.Init();

	st.Push(1);
	st.Push(2);
	st.Push(3);
	st.Push(4);

	cout << st.Top() << endl;

    st.Destroy();

    Person p1;
    p1.Init("张三",18,12345);
    p1.Print();
    p1.age++;//报错

    QU qu;
    QueueInit(&qu);

	return 0;

}

C++中class定义类相比于C语言中struct结构体的区别:

  1. class中可以定义函数
  2. 增加了访问限定符

1.2 访问限定符

  • C++一种实现封装的方式,用类将对象的属性与方法结合在一起,让对象更加完善,通过访问权限选择性的将其接口提供给外部的用户使用。
  • public修饰的成员在类外可以直接被访问;protected和private修饰的成员在类外不能直接被访问,protected和private是一样的,以后继承章节才能体现它们的区别。
  • 访问权限作用域从该访问限定符出现的位置开始直到下一个访问限定符出现为止,如果后面没有访问限定符,作用域到 } 即类结束。
  • class定义成员没有被访问限定符修饰时默认为private/protected,需要给别人使用的成员函数会放为public。
代码语言:javascript
复制
//具体让什么公有什么私有取决于自己,一般成员函数设为公有,成员变量设为私有,
//因为成员变量不希望被改变,私有的在类外不能用,在类内成员函数能用

#include<iostream>
#include<assert.h>

using namespace std;
class Stack
{
public:
	void Init(int n = 4)
	{
		array = (int*)malloc(sizeof(int) * n);
		if (array == nullptr)
		{
			perror("malloc申请空间失败");
			return;
		}
		capacity = n;
		top = 0;
	}

	void Push(int x)
	{
		//...扩容
		array[top++] = x;
	}

	int Top()
	{
		assert(top > 0);
		return array[top - 1];
	}

	void Destroy()
	{
		free(array);
		array = nullptr;
		top = capacity = 0;
	}

private:
		int* array;
		size_t capacity;
		size_t top;
};

int main()
{
	//类名就是类型,用类型定义对象
	Stack st;

	st.Init();

	st.Push(1);
	st.Push(2);
	st.Push(3);
	st.Push(4);

	cout << st.Top() << endl;

	st.Destroy();

	return 0;

}

1.3 类域

  • 类定义了一个新的作用域,类的所有成员都在类的作用域中,在类体外定义成员时,需要使用 :: 作用域操作符指明成员属于哪个类域。
  • 类域影响的是编译的查找规则,下面程序中Init如果不指定类域Stack,那么编译器就把Init当成全局函数,那么编译时,找不到_array等成员变量的声明或定义在哪里,就会报错。指定类域Stack,就是知道Init是成员函数,当前域找不到_array等成员,就会到类域中去查找。(悟)

比较短小的函数就在类里面去定义,默认是内联函数,长一点的函数不在类里面去定义在类外面去定义,在.cpp文件里面去定义,做函数声明和定义的分离。下面展现的就是标准的类的声明和定义分离。

代码语言:javascript
复制
Stack.h

#pragma once
#include<iostream>
#include<assert.h>
using namespace std;

class Stack
{
public:
	void Init(int n = 4);
private:
	int* _array;
	int _top;
	int _capacity;
};
代码语言:javascript
复制
Stack.cpp

#include"Stack.h"

//声明和定义分离需要指定类域
void Stack::Init(int n)
{
	_array = (int*)malloc(sizeof(int) * n);
	if (_array == nullptr)
	{
		perror("malloc file!");
		return;
	}
	_capacity = n;
	_top = 0;
}
代码语言:javascript
复制
Test.cpp

#include"Stack.h"

int main()
{
	Stack st;
	st.Init();
	return 0;
}

2. 实例化

2.1 实例化概念

  • 用类类型在物理内存中创建对象的过程,称为类实例化出对象。
  • 类是对象进行一种抽象描述,是一个模型一样的东西,限定了类有哪些成员变量,这些成员变量只是声明,没有分配空间,用类实例化出对象时,才会分配空间。
  • 一个类可以实例化出多个对象,实例化出的对象,占用实际的物理空间,存储类成员变量(例如:类是设计图纸,设计图规划出有多少个房间,房间功能等,但是没有实体的存在,也不能住人,用设计图来建造一个实际的房子,就叫实例化,能够住人。同样类就像设计图一样,不能存储数据,实例化出的对象分配物理内存才能存储数据)。

成员变量是声明,不是定义,声明不开辟空间,定义开辟空间。

代码语言:javascript
复制
#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 year;

int main()
{
    //类实例化出对象,1->N的关系,类里面不能存储数据
	Date d1;
	Date d2;

	d1.Init(2024, 9, 22);
	d2.Init(2024, 9, 23);
	d1.Print();
	d2.Print();

	return 0;
}

2.2 对象的大小

分析一下类对象中有哪些成员呢?类实例化出的每个对象,都有独立的数据空间,所以对象中肯定包含成员变量,那么成员函数是否包含呢?

首先函数被编译后是一段指令,对象中没办法存储,这些指令存储在一个单独的区域(代码段),如果对象中非要存储的话,只能是成员函数的指针。再分析一下,对象中是否有存储指针的必要呢?Date实例化d1和d2两个对象,d1和d2都有各自独立的成员变量_year/_month/_day存储各自的数据,但是d1和d2的成员函数Init/Print指针却是一样的,存储在对象中就浪费了。如果Date实例化出100个对象,那么成员函数指针就重复存储100次,太浪费了。这里需要再说一下,其实函数指针是不需要存储的,函数指针是一个地址,调用函数被编译成汇编指令[call地址],其实编译器在编译链接时,就要找到函数的地址,不是在运行时找,只有动态多态是在运行时找,就需要存储函数地址,这个我们后面讲解。

上面我们分析了对象只存储成员变量,C++规定类实例化的对象也要符合内存对齐的规则。

内存对齐规则

  • 第一个成员变量在与结构体偏移量为0的地址处。
  • 其他成员变量要对齐到对齐数的整数倍处。
  • 注意:对齐数=编译器默认的一个对齐数与该成员大小的较小值。
  • VS中默认的对齐数为8。
  • 结构体总大小为:最大对齐数(所有变量类型最大者与默认对齐参数取最小)的整数倍处。
  • 如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最大对齐数的整数倍处,结构体的整体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。
代码语言:javascript
复制
#include<iostream>
using namespace std;
// 计算⼀下A/B/C实例化的对象是多⼤?

class A
{ 
public:
    void Print()
{
    cout << _ch << endl;
}
private:
    char _ch;
    int _i;
}

//对于没有成员变量的类对象,开1个字节,占位,不存储有效数据
//表示对象的存在
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;
}

上⾯的程序运⾏后,我们看到没有成员变量的B和C类对象的⼤⼩是1,为什么没有成员变量还要给1个字节呢?因为如果⼀个字节都不给,怎么表⽰对象存在过呢!所以这⾥给1字节,纯粹是为了占位标识对象存在。

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 指针。
代码语言:javascript
复制
#include<iostream>
using namespace std;

//编译器自己回加上this,我们不必加上
class Date
{
public:
	//void Init(Date* const this, int year, int month, int day)
	void Init(int year, int month, int day)
	{
		//this->_year = year;
		_year = year;
		_month = month;
		_day = day;
	}
	//void Print(Date* const this)
	void Print()
	{
		//this = nullptr;this不能被修改,但是this指向的内容可以被修改
		cout << this->_year << '/' << _month << '/' << _day << endl;
	}
private:
	//声明
	int _year;
	int _month;
	int _day;
};

//定义
int year;

int main()
{
	Date d1;
	Date d2;

	//d1.Init(&d1,2024,9,20)
	d1.Init(2024, 9, 20);

	//d2.Init(&d2,2024,9,22)
	d2.Init(2024, 9, 22);

	//d1.Print(&d1);
	d1.Print();

	//d2.Print(&d2);
	d2.Print();

	return 0;
}

【 习题三道】

1.下⾯程序编译运⾏结果是(C)

A、编译报错 B、运⾏崩溃 C、正常运⾏

代码语言:javascript
复制
#include<iostream>
using namespace std;

class A
{ 
public:
    void Print()
    {
        cout << "A::Print()" << endl;
    }
private:
    int _a;
}

int main()
{
    A* p = nullptr;
    p->Print();

    return 0;
}

2.下⾯程序编译运⾏结果是(B)

A、编译报错 B、运⾏崩溃 C、正常运⾏

代码语言:javascript
复制
#include<iostream>
using namespace std;

class A
{ 
public:
    void Print()
    {
        cout << "A::Print()" << endl;
        cout << _a << endl;
    }
private:
    int _a;
};

int main()
{
    A* p = nullptr;
    p->Print();

    return 0;
}

【分析】

3. this指针存在内存哪个区域的 (A)

A. 栈 B.堆 C.静态区 D.常量区 E.对象⾥⾯

this是一个隐含的形参。局部变量,形参存在函数栈帧里面。

4. C++和C语言实现Stack对比

面向对象三大特性:封装、继承、多态,下面我们来初步了解一下封装。

  • C++中数据和函数都放在了类里面,通过访问限定符进行了限制,不能再随意通过对象进行修改数据,这是C++封装的一种体现,这个是最重要的变化,这里的封装的本质是一种更严格规范的管理,避免出现乱访问修改的问题。封装不仅仅是这样,后面需要我们不断地学习。
  • C++中有一些相对方便的语法,比如:Init给的缺省参数会方便很多,成员函数每次不需要传对象地址,因为this指针隐含的传递了,方便了很多,使用类型不再需要typedef直接用类名就很方便。
  • 后面我们用STL中的适配器实现的Stack可以感受下C++的魅力。
【C实现Stack】
代码语言:javascript
复制
C实现Stack

#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

void STInit(ST* ps)
{
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

void STDestroy(ST* ps)
{
	assert(ps);

	free(ps->a);
	ps->a = NULL;
	ps->top = ps->capacity = 0;
}

void STPush(ST* ps, int x)
{
	assert(ps);

	//判断空间是否充足
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
		STDataType* tmp = (STDataType*)realloc(ps->a, newCapacity * sizeof(int));
		if (tmp == NULL)
		{
			perror("realloc file!");
			return;
		}
		ps->a = tmp;
		ps->capacity = newCapacity;
	}

	ps->a[ps->top++] = x;
}

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 main()
{
	ST s;
	STInit(&s);

	STPush(&s, 1);
	STPush(&s, 2);
	STPush(&s, 3);
	STPush(&s, 4);

	while (!STEmpty(&s))
	{
		printf("%d ", STTop(&s));
		STPop(&s);
	}

	STDestroy(&s);

	return 0;
}
【C++实现Stack】
代码语言:javascript
复制
C++实现Stack

#include<iostream>
#include<assert.h>
using namespace std;

class Stack
{
	typedef int STDataType;
public:
	//成员函数
	void Init(int n = 4)
	{
		_a = (STDataType*)malloc(sizeof(STDataType) * n);
		_top = 0;
		_capacity = n;
	}

	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;
	int _top;
	int _capacity;
};

int main()
{
	Stack s;
	s.Init();
	s.Push(1);
	s.Push(2);
	s.Push(3);
	s.Push(4);

	while (!s.Empty())
	{
		printf("%d ", s.Top());
		s.Pop();
	} 

	s.Destroy();

	return 0;
}

期待下次的《类和对象(中)》

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-10-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 类的定义
    • 1.1 类定义格式
    • 1.2 访问限定符
    • 1.3 类域
  • 2. 实例化
    • 2.1 实例化概念
    • 2.2 对象的大小
  • 3. this指针
  • 4. C++和C语言实现Stack对比
    • 【C实现Stack】
    • 【C++实现Stack】
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档