结构体
(1)结构体定义方法。
#include <iostream>
using namespace std;
typedef struct books { // typedef给books定义别名 a
string title;
string autor;
string subject;
int book_id;
} a; // 结构体声明完了要加 分号
int main() {
a book1;
a book2;
book1.book_id = 20;
book1.subject = "yang";
cout << book1.subject << endl;
}
#include <iostream>
using namespace std;
struct books { // 常规定义方法
string title;
string autor;
string subject;
int book_id;
};
int main() {
books book1;
books book2;
book1.book_id = 20;
book1.subject = "yang";
cout << book1.subject << endl;
}
#include <iostream>
using namespace std;
int main() {
struct books { // 这种情况必须定义内联的结构体
string title;
string autor;
string subject;
int book_id;
} book1, book2, a[10];
book1.book_id = 20;
book1.subject = "yang";
cout << book1.subject << endl;
a[1].subject = "yang";
}
(2)结构体构造函数
#include <iostream>
#include <string>
using namespace std;
struct node{
int data;
string str;
char x;
//自定义初始化函数
void init(int a, string b, char c){
this->data = a;
this->str = b;
this->x = c;
}
node() :x(), str(), data(){} // 无参数的构造函数数组初始化时调用,注意构造函数结尾没有分号
node(int a, string b, char c) :x(c), str(b), data(a){} // 构造函数表
}N[10];
int main()
{
N[0] = { 1,"hello",'c' };
N[1] = { 2,"c++",'d' }; //无参默认结构体构造体函数
N[2].init(3, "java", 'e'); //自定义初始化函数的调用
N[3] = node(4, "python", 'f'); //有参数结构体构造函数
N[4] = { 5,"python3",'p' };
//现在我们开始打印观察是否已经存入
for (int i = 0; i < 5; i++){
cout << N[i].data << " " << N[i].str << " " << N[i].x << endl;
}
system("pause");
return 0;
}
>>>
1 hello c
2 c++ d
3 java e
4 python f
5 python3 p
(3)结构体成员的访问
非结构体指针访问用.
,结构体指针用->
访问。
c++的结构体和c的结构体区别
c++语言将struct当成类来处理的,所以c++的struct可以包含c++类的所有东西,例如构造函数、析构函数,友元等,c++的结构体和c++类的唯一不同就是struct成员默认的是public,c++默认private。而c语言struct不是类,不可以有函数,也不能使用类的特征例如public等关键字,也不可以有static 关键字。