- 类
- 结构体
- test
- LeetCode链表定义:采用结构体
#includeusing namespace std; class Person { private: // 只能在类里调用 无private的话对于成员变量,class默认是private,结构体默认为public int age, height; double money; string books[100]; public: // 可在外部调用 string name; void say() { cout << "I'm " << name << endl; } int get_age() { return age; } void add_money(double x) { money += x; } int get_money() { return money; } }; // 记得加分号
若不加修饰符(private/public),则对于成员变量,class默认是private,结构体默认为public
结构体struct Person0
{
int age, height;
double money;
// 构造函数,无类型,名称与结构体一致;可以有多个,一般写个无参构造,避免报错
Person0(){}
Person0(int _age, int _height): age(_age), height(_height){}
// Person0(int _age, int _height, double _money)
// {
// age = _age;
// height = _height;
// money = _money;
// }
// 该写法运行效率快一些
Person0(int _age, int _height, double _money):age(_age), height(_height), money(_money) {}
};
test
int main(){
Person c;
Person persons[1000];
// c.age = 18;
cout << c.get_age() << endl;
c.add_money(1000000);
cout << c.get_money() << endl;
// 结构体
cout << "结构体" << endl;
Person0 p(18, 180, 100.0); // 需定义三个参数的构造函数
cout << p.age << " " << p.height << " " << p.money << endl; // 18 180 100
// 另一种写法,按变量顺序初始化;
// 需要 无构造函数 或 构造函数参数有3个,否则该句报错;未初始化的参数默认为0
Person0 k = {18, 180, 100.0};
cout << k.age << " " << k.height << " " << k.money << endl; // 18 180 100
Person0 q = {18, 180}; // 需要 无构造函数 或 构造函数参数有2个,否则该句报错;未初始化的参数默认为0
cout << q.age << " " << q.height << " " << q.money << endl; // 18 180 0
return 0;
}
LeetCode链表定义:采用结构体



