类和结构体基本一样,唯一的不同就是:如果不声明是private或public,则类默认为private,结构体默认为public。
类
类的定义
#include<iostream>
using namespace std;
class Person{
private: //私有型,只能在类里调用
int age,height;
double money
string books[100];
int get_height(){
return height;
}
public: //公共型,可以在类里和类外调用
stirng name;
void say(){
cout << "I`m" << name << endl;
}
int get_age(){
return age;
}
void add_money(double x){
money += x;
}
private:
string books[100];
}; //末尾一定要加 ;
int main(){
return 0;
}
类的使用
#include<iostream>
using namespace std;
class Person{
private: //私有型,只能在类里调用
int age,height;
double money
string books[100];
int get_height(){
return height;
}
public: //公共型,可以在类里和类外调用
stirng name;
void say(){
cout << "I`m" << name << endl;
}
int get_age(){
return age;
}
void add_money(double x){
money += x;
}
private:
string books[100];
}; //末尾一定要加 ;
int main(){
Person c;
c.name = "lxy";
// c.age = 18; // 错误的,age为私有变量
c.add_money(1000000);
cout << c.get_age() << endl;
return 0;
}
类的构造函数
#include<iostream>
using namespace std;
struct Person{
int age,height;
double money;
Person(int _age,int _height,double _money){
age = _age;
height = _height;
money = _money;
} //构造函数
Person(int _age,int _height,double _money) : age(_age),height(_height),money(_money) {} //另一种定义构造函数的方式
};
int main(){
Person c{19,175,10000000};
cout << c.age << endl;
return 0;
}
链表
#include<iostream>
using namespace std;
struct Node{
int val;
Node* next;
Node(int _val) : val(_val),next(NULL) {}
};
int main(){
Node* p = new Node(1); //new:动态开辟一个结构体
auto q = new Node(2); //auto猜类型,即为Node*
auto o = new Node(3);
p->next = p; //p的next指针指向自己,形成自环。ps:如果p是一个指针,要用"->"来调用成员标量,如果不是指针,则可以通过p.next来调用
p->next = q; //p中的next指针指向q,即构造一个链表
q->next = o;
Node* head = p;
//头插一个节点
Node* u = new Node(4);
u->next = head;
head = u;
//删除节点
head->next = head->next->next;
//链表的遍历方式
for(Node* i = head;i;i = i->next){
cout << i->val << endl;
}
return 0;
}