类和对象 1
1、类的定义
C++ 中可以用 struct 定义一个类,但更多的是使用 class 定义类
举例:
C 语言中的结构体
// C 语言:仅能定义变量,不能定义函数
struct Student {
char name[20];
int age;
// 错误!C 不允许结构体里写函数
// void show() { ... }
};
C++ 中的类
// C++ 类:变量 + 函数 + 访问控制
class Student {
private:
// 成员变量(属性)
std::string name;
int age;
public:
// 成员函数(方法)
void setInfo(std::string n, int a) {
name = n;
age = a;
}
void showInfo() {
std::cout << name << " " << age << std::endl;
}
};
- C++ 中 struct 也可以定义类,C++ 兼容 C 中 struct 的用法,同时 struct 升级成了类,明显的变化是 struct 中可以定义函数,一般情况下我们还是推荐用 class 定义类。
类的两种定义方法:
- 声明和定义全部放在类体中
// 定义一个栈的结构体
class Stack {
public:
// 初始化栈
void Init(int n = 4) {
array = (int*)malloc(() * n);
( == array) {
();
;
}
capacity = n;
top = ;
}
* array;
capacity;
top;
};




