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;
}
};
访问控制(private、public)
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也更容易