c++兼容c
- C语言面向过程 – 数据和方法是分离的
- CPP面向对象 – 数据和方法是封装在一起的
- struct可以定义类但C++当中经常用class来定义类
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;
}
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://改成public就可以运行了,因为private是私有的,不能在main访问
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;
return 0;
}
类和对象
类的大小
结构体内存对齐
class Date
{
public:
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;
}



