c++入门 类和对象(上)

类和对象

1.类的定义

1.1 类定义格式

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

#define  _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<assert.h>
using namespace std;
class Stack
{
public:
	//成员函数
	void Iint(int n = 4)
	{
		int*array = (int*)malloc(sizeof(int) * n);
		if (nullptr == array)
		{
			perror("malloc申请空间失败");
			return;
		}
		capacity = n;
		top  = 0;
	}
	void Push(int x)
	{
		//...扩容
		array[top++] = x;

	}
	int Top()
	{
		assert(top > 0);
		return array[top - 1];
	}
	void Destory()
	{
		free(array);
		array = nullptr;
		top = capacity = 0;
	}
private:
	//成员变量
	int* array;
	size_t capacity;
	size_t top;
};//分号不能省
//类名就是类型
int main(){
	Stack st;
	st.Iint();
	st.Push(1);
	st.Push(2);
	cout << st.Top() << endl;
	st.Destory();
	return 0;

}

类:

class Data
{
public:
	void Init(int year, int month, int day)
	{
		_year = year;
		_month = month;
		_day = day;
	}
private:
	//为了区分成员变量,一般习惯上成员变量会加一个特殊标识符,如_或者m开头
	int _year; //year_;m_year
	int _month;
	int _day;

};
int main()
{
	Data d;
	d.Init(2024, 8, 9);
	return 0;
}
//c++升级struct升级成了类
//1.类里面可以定义函数
//2.struct 名称就可以代表类型

//c++兼容c中struct的用法
typedef struct ListNodeC
{
	struct ListNodeC* next;
	int val;
}LTNode;
// 不再需要typedef,ListNodeCPP就可以代表类型
struct ListNodeCPP
{
	void Init(int x)
	{
		next = nullptr;
		val = x;
	}
	ListNodeCPP* next;
	int val;
};
int main()
{
	return 0;
}

1.2 访问限定符

(1) C++⼀种实现封装的⽅式,⽤类将对象的属性与方法结合在⼀块,让对象更加完善,通过访问权限选择性的将其接口提供给外部的用户使用。
(2)public修饰的成员在类外可以直接被访问protected和private修饰的成员在类外不能直接被访问,protected和private是⼀样的。
(3)访问权限作用域从该访问限定符出现的位置开始直到下⼀个访问限定符出现时为止,如果后面没有访问限定符,作用域就到 }即类结束。
(4)class定义成员没有被访问限定符修饰时默认为private,struct默认为public。
(5) ⼀般成员变量都会被限制为private/protected,需要给别人使用的成员函数会放为public。
访问限定符

1.3 类域

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

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 实例化概念

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

class Data {
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, _month, _day;
};
int main()
{
	//1->n
	//Date类实例化出对象d1和d2
	Data d1;
	Data d2;
	d1.Init(2024, 8, 9);
	d1.print();
	d1.Init(2024, 8, 8);
	d1.print();
	return 0;
}

Data

2.2 对象大小

Date实例化d1和d2两个对象,d1和d2都有各自独立的成员变量
_year/_month/_day存储各自的数据,但是d1和d2的成员函数Init/Print指针却是⼀样的,存储在对象中就浪费了。如果用Date实例化100个对象,那么成员函数指针就重复存储100次,太浪费了。
对象大小
内存对齐规则
(1) 第⼀个成员在与结构体偏移量为0的地址处。
(2) 其他成员变量要对齐到某个数字(对齐数)的整数倍的地址处。
(3) 注意:对齐数 = 编译器默认的⼀个对齐数 与 该成员大小的较小值。
(4)VS中默认的对齐数为8
(5) 结构体总大小为:最⼤对齐数(所有变量类型最⼤者与默认对齐参数取最小)的整数倍。
(6)如果嵌套了结构体的情况,嵌套的结构体对齐到自己的最⼤对齐数的整数倍处,结构体的整体大小就是所有最大对齐数(含嵌套结构体的对齐数)的整数倍。

#define  _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;
//计算A/B/C实例化对象多大
class A
{
public:
	void print()
	{
		cout << _ch << endl;
	}
private:
	char _ch;
	int _i;
};
class B
{
	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字节,纯粹是为了占位标识对象存在。

3. this指针

Date类中有 Init 与 Print 两个成员函数,函数体中没有关于不同对象的区分,C++给了⼀个隐含的this指针解决这里的问题。
(1) 编译器编译后,类的成员函数默认都会在形参第一个位置,增加⼀个当前类类型的指针,叫做this指针。比如Date类的Init的真实原型为, void Init(Date* const this, int year,int month, int day)
(2) 类的成员函数中访问成员变量,本质都是通过this指针访问的,如Init函数中给_year赋值, this->_year = year;
(3)C++规定不能在实参和形参的位置显示的写this指针(编译时编译器会处理),但是可以在函数体内显示使用this指针。

class Date
{
public:
	//应该是怎么写的,但是this是隐含的,不能在实参和形参的位置显⽰的写this指针 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;
		_month = month;
		_day = day;

	}
	 void Print(Date* const this)
	void Print()
	{
		cout << _year << "/" << _month << "/" << _day << endl;
	 }
private:
	// 这⾥只是声明,没有开空间
	int _year, _month, _day;//int 后面有空格
};
int main()
{
	 Date类实例化出对象d1和d2
	Date d1, d2;
	// d1.Init(&d1, 2024, 3, 31);
	 d1.Init( 2024, 3, 31);
	 d1.Print();
	 // d1.Init(&d1, 2024, 2, 31);
	 d1.Init(2024, 2, 31);
	 d1.Print();

	return 0;
}

this指针
活学活用
1.

#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;
}

运行结果:程序正常运行
原因:成员函数的指针是在编译时确定的,没有存在对象中,所以这里虽然写了p->,但是没有解引用
2.

#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指针存在内存哪个区域的?栈区;原因:vs系列编译器,this通过寄存器传递。

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

⾯向对象三⼤特性:封装、继承、多态。
(1)C++中数据和函数都放到了类里面,通过访问限定符进行了限制,不能再随意通过对象直接修改数据,这是C++封装的⼀种体现,这个是最重要的变化。这里的封装的本质是⼀种更严格规范的管理,避免出现乱访问修改的问题。
(2) C++中有⼀些相对方便的语法,比如Init给的缺省参数会方便很多,成员函数每次不需要传对象地址,因为this指针隐含的传递了,方便了很多,使⽤类型不再需要typedef用类名就很方便。
C实现Stack代码

#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代码

//c++实现stack
#include<assert.h>
typedef int STDatatype;
class  Stack {
public:
	//成员函数
	void Init(int n=4)
	{
		_a = (STDatatype*)malloc(sizeof(STDatatype)*n);
		if (nullptr == _a)
		{
			perror("malloc fail");
			exit(1);
		}
		_capacity = n;
		_top = 0;
	}
	void Push(STDatatype x) {
		if (_top == _capacity)
		{
			int newcapacity = _capacity * 2;
			int* tmp = (int*)realloc(_a, sizeof(int) * newcapacity);
			if (nullptr == tmp)
			{
				perror("realloc fail");
				exit(1);
			}
			_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;
		_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;
}

栈的运行

总结

以上就是类和对象(上)的全部内容,写的非常详细,希望大家看完这篇博客有收获,可以一键三连鼓励作者!!!!!

  • 35
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懒羊羊大王&

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值