C++(The Cherno)-Day5

本文介绍了C++中的类(class)和struct的基本概念,讨论了它们之间的区别,以及如何在实践中选择和使用。通过实例展示了如何定义和操作类,包括访问控制、私有变量和公共接口的运用。
摘要由CSDN通过智能技术生成

C++(The Cherno)-Day5

CLASSES in C++

c++中的类是一种将数据和函数组织在一起的方式

c++的类默认是私有的

定义如下:

class player {
 int x, y;
 int speed;
 void move(int a, int b){
     x += a * speed;
     y += b * speed;
 }
};

访问控制(privatepublic

class player {
public:
 int x, y;
 int speed;
private:
 void move(int a, int b){
     x += a * speed;
     y += b * speed;
 }
};

CLASSES vs STRUCTS in C++

区别:

作用上:class默认private,struct默认public。
使用上:引入struct是为了让C++向后兼容C

推荐选用:

若只包含一些变量结构或POD(plain old data)时,选用struct。例如数学中的向量类

struct常用来替代一个结构中的一些数据

struct Vec2{
 float x, y;
 void Add(const Vec2& other){
     x += other.x;
     y += other.y;
 }
};

若要实现很多功能的类,则选用class。

本质上,class与struct没有区别。

HOW to Write a C++ Class

写一个完整的c++的类如下,一般我们从需求入手,先在main函数中写出所要实现的功能,再在class中进行定义补充,由表及里,再定义一些变量。

对于c++私有的变量我们常用m_开头,这算也是一种约定俗成的定义方法,这可以让代码变得更干净更易读

#include <iostream>

class Log
{
public:
	const int LogLevelError = 0;
	const int LogLevelWarning = 1;
	const int LogLevelInfo = 2;
private:
	int m_Level = LogLevelInfo;
public:
	void SetLevel(int level)
	{
		m_Level = level;
	}

	void Error(const char* message)
	{
		if(m_Level >= LogLevelError)
			std::cout << "[ERROR]" << message << std::endl;
	}
	void Warn(const char* message)
	{
		if (m_Level >= LogLevelWarning)
			std::cout << "[WARNING]" << message << std::endl;
	}
	void Info(const char* message)
	{
		if (m_Level >= LogLevelInfo)
			std::cout << "[INFO]" << message << std::endl;
	}

};

int main() 
{
	Log Log;
	Log.SetLevel(Log.LogLevelInfo);
	Log.Error("Hello");
	Log.Warn("Hello");
	Log.Info("Hello");

	std::cin.get();
	return 0;
}

在编写class时,我们也会把不同功能的public分开,这样可以使代码更清晰,查找bug也更容易

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值