一、struct的定义、访问成员
#include<bits/stdc++.h>
using namespace std;
//定义结构体
struct student{
//公有成员(可以省略) 结构体外部可以访问
public:
int id;
string name;
//私有成员:只有结构体内部可以访问
private:
int age;
};
//定义结构以变量
struct student a;
int main()
{
cin>>a.id;//正确:可以访问公有成员
cin>>a.age;//错误:不能直接访问
return 0;
}
可以用 . 来访问结构体的成员,而私有成员不能直接访问,我们可以在公有成员里做一个“接口”专门用来更改或者读取私有成员:
#include<bits/stdc++.h>
using namespace std;
//定义结构体
struct student{
//公有成员(可以省略) 结构体外部可以访问
public:
int id;
string name;
void put_age(int num){
age=num;
}
int get_age(){
return age;
}
//私有成员:只有结构体内部可以访问
private:
int age;
};
//定义结构以变量
struct student a;
int main()
{
int x;
cin>>x; //输入18
a.put_age(x); //age更改为18
cout<<a.get_age()<<endl;//读取age,并输出18
return 0;
}
二、重载操作符(一般用于排序)
重载操作符的语法
returnType operator op(参数列表) { // 操作符的实现 }
其中:
returnType
是操作符返回的类型。op
是要重载的操作符。参数列表
是操作符所需的参数列表。// 操作符的实现
是操作符的具体实现代码。
这里给出关系运算符<和>的重载操作
struct Student{
string name;
int score;
// 第一个const表明 结构体t的值不会改变
// 第二个const表明 结构体this的值不会改变
bool operator < (const Student& t) const{
return score < t.score;
}
bool operator > (const Student& t) const{
return score > t.score;
}
}a[N];
其中的const修饰符可以省略,但结构体的值就可以在重载函数中进行更改。
三、构造函数
- 默认构造函数:如果没有显式定义任何构造函数,编译器会自动生成一个默认构造函数。默认构造函数会将所有成员变量初始化为 0 或空值。
- 参数化构造函数:参数化构造函数可以接受参数,并使用这些参数来初始化结构体对象的成员变量。
- 拷贝构造函数:拷贝构造函数用于创建结构体对象的副本。它接受一个结构体对象作为参数,并使用该参数来初始化新创建的结构体对象的成员变量。
#include<bits/stdc++.h>
using namespace std;
struct Point {
int x;
int y;
// 默认构造函数
Point() : x(0), y(0) {}
// 参数化构造函数
Point(int x, int y) : x(x), y(y) {}
// 拷贝构造函数
Point(const Point& other) : x(other.x), y(other.y) {}
};
int main()
{
//默认构造函数
struct Point a;
cout<<a.x<<" "<<a.y<<endl;
//参数构造函数
struct Point b(3,9);
cout<<b.x<<" "<<b.y<<endl;
//拷贝构造函数
struct Point c(b);
cout<<c.x<<" "<<c.y<<endl;
return 0;
}