结构体是特殊形态的类,与类的区别:
结构体的默认访问权限是public,也就是说当你创建数据成员的时候,默认是属于public类,
存在的主要原因:与C语言保持兼容。
//结构体 struct 学生信息
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Student {
int num;
string name;
char sex;
int age;
};
int main(){
Student stu = {97001, "Lin Lin", 'F' , 19};
cout << "Num: " << stu.num << endl;
cout << "Name: " << stu.name << endl;
cout << "Sex: " << stu.sex << endl;
cout << "Age: " << stu.age << endl;
return 0;
}
联合体中的成员是“互斥”的,不会同时有效,但优点是成语之间共用相同的内存单元.
示例
// 联合体
#include <string>
#include <iostream>
using namespace std;
class ExamInfo{
private:
string name;
enum {GRADE, PASS, PERCENTAGE} mode; //三种不同的计分方式
union { //都是指成绩
char grade;
bool pass;
int percent;
};
public:
ExamInfo(string name, char grade)
: name(name),mode(GRADE),grade(grade){}
ExamInfo(string name, bool pass)
: name(name),mode(PASS),pass(pass){}
ExamInfo(string name,int percent)
: name(name),mode(PERCENTAGE),percent(percent){}
void show();
};
void ExamInfo::show(){
cout << name << ": ";
switch (mode) {
case GRADE: cout << grade; break;
case PASS: cout << (pass ? "PASS" : "FAIL"); break;
case PERCENTAGE: cout << percent; break;
}
cout << endl;
}
int main(){
ExamInfo course1("English", 'B');
ExamInfo course2("Calculus", true);
ExamInfo course3("C++ Programming", 85);
course1.show();
course2.show();
course3.show();
return 0;
}