1.结构体定义
`
struct 结构体名 数组名[元素个数] = { {} , {} , ... {} }
`
struct student { string name; //默认是公共权限 }// 使用1student stu;stu.name = "詹丹"// 使用1student stu2 = {"占山"}
复制代码
2.class 定义
`
语法: class 类名{
成员属性;
成员函数
}
`
// 简单的类class Student { string name;//默认是私有权限}// 调用Student stu;stu.name = "ddd";//错误,默认为私有属性,没有访问权限
复制代码
3. struct 与 class 的区别
>a,struct 属性默认是公有权限;class 默认是私有权限
>b. struct 可以和 class 当类使用,拥有:构造函数,成员函数,成员变量,析构函数,
>c. 都可以被继承,struct 被子类继承,里面的成员函数,成员变量都是 public 权限,而 class 具体根据权限的不同显示不同的权限
>d.class 可以使用模板,而 struct 不能
4. struct 可以当类使用
#include <iostream>using namespace std;struct Student { Student(int age); ~Student(); void show(); int m_age;};Student::Student(int age) { this->m_age = age;}Student::~Student() {}void Student::show() { cout <<this->m_age << endl;}int main() { Student stu(15); stu.show(); return 0;}
复制代码
class 类
#include <iostream>using namespace std;class Student {public: Student(int age); ~Student(); void show();private: int m_age;};Student::Student(int age) { this->m_age = age;}Student::~Student() {}void Student::show() { cout <<this->m_age << endl;}int main() { Student stu(15); stu.show(); return 0;}
复制代码
评论