类和对象1

面向对象的三大特性

  • 封装(类的定义和特性)
  • 继承
  • 多态
  • 其他特性:抽象、反射

公有和私有

成员变量和成员函数加访问限定符来限定对它的访问
在这里插入图片描述
公有的

struct Student//类
{
	void SetStudentInfo(const char* name, const char* gender, int age)//方法--成员函数
	{
		strcpy(_name, name);
		strcpy(_gender, gender);
		_age = age;
	}
		void PrintStudentInfo()
    {
		cout << _name << " " << _gender << " " << _age << endl;
	}
	char _name[20];//成员变量
	char _gender[3];
	int _age;
};
int main()
{
	Student s;//对象
	s.SetStudentInfo("Peter", "男", 18);//调用方法
	s.PrintStudentInfo();//调用方法
	return 0;
}

C和C++公有和私有

  • C语言面向过程 – 数据和方法是分离的
  • CPP面向对象 – 数据和方法是封装在一起的
  • C++即有面向对象也有面向过程,因为C++兼容C
  • c++兼容c,但c++中struct已经不仅仅是结构体,struct同时升级成类
  • struct可以定义类但C++当中经常用class来定义类
    在这里插入图片描述
//C
namespace bitc//命名空间解决命名冲突的问题
{
	struct Stack
	{
		int* a;
		int top;
		int capacity;
	};
	void StackInit(struct Stack* ps){}
	void StackPush(struct Stack* ps, int x){}
	// ...
}
// CPP--不写访问限定符,成员函数和成员变量默认为私有的,则会编译报错
namespace bitcpp
{
	struct Stack
	{
	public:
		void Init(){}
		void Push(int x){}
		void Pop(){}
		void Destory(){};
	private:
		int* a;
		int top;
		int capacity;
	};
}
int main()
{
	struct bitc::Stack stc;
	bitc::StackInit(&stc);
	bitc::StackPush(&stc, 1);
	bitc::StackPush(&stc, 2);

	bitcpp::Stack stcpp;
	stcpp.Init();
	stcpp.Push(1);
	stcpp.Push(2);
	//stcpp.top = 0;//改成public就可以运行了,因为private是私有的,不能在main访问
	return 0;
}

在这里插入图片描述

类和对象

在这里插入图片描述

类的大小

结构体内存对齐
情况1
在这里插入图片描述

情况2
在这里插入图片描述

this-重点

class Date
{
public:
  //void Display(Date* this)---不能这样写,这是编译器干的
	void Display()
	{
		cout << _year << "-" << _month << "-" << _day << endl;
		//cout << this->_year << "-" << this->_month << "-" << this->_day << endl;---可以这样写
	}
	// void Init(Date* this, int year, int month, int day)---不能这样写,这是编译器干的
	void Init(int year, int month, int day)
	{
		// 成员函数里面。我们不加的话,默认会在成员前面this->
		// 我们也可以显示的在成员前面this->
		_year = year;
		_month = month;
		_day = day;
		// 对象可以调用成员函数,成员函数中还可以调用成员函数
		// 因为有this指针
		//this->Display();
	}
private:
	int _year; // 年
	int _month; // 月
	int _day; // 日
};
int main()
{
	Date d1;//类实例化对象
	Date d2; 
	d1.Init(2021, 10, 8); // d1.Init(&d1, 2021, 10, 8);
	d2.Init(2022, 10, 8); // d2.Init(&d2, 2021, 10, 8);
	d1.Display(); // d1.Display(&d1);
	d2.Display(); // d2.Display(&d2);
	return 0;
}

在这里插入图片描述
在这里插入图片描述1、this指针存在哪
在这里插入图片描述

2、this注意点:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值