【C++】数据结构 struct,结构体相关操作
代码:
#include <iostream>
#include <cstring>
using namespace std;
struct Book{
char title[50];
char author[50];
double price;
int bookId;
};
void printBook(struct Book book){
cout << "书名:" << book.title <<endl;
cout << "作者:" << book.author <<endl;
cout << "价格:" << book.price <<endl;
cout << "ID:" << book.bookId <<endl;
}
int main(){
Book book1;
Book book2;
strcpy(book1.title,"C++ 教程");
strcpy(book1.author, "Runoob");
book1.price = 51.50;
book1.bookId = 123456;
strcpy(book2.title, "Python 教程");
strcpy(book2.author, "GuidoVanRossum");
book2.price = 39.90;
book2.bookId = 456789;
printBook(book1);
printBook(book2);
return 0;
}
运行结果:
结构体和数组:
#include <iostream>
#include <string>
using namespace std;
struct Book{
string title;
string author;
double price;
};
int main(){
struct Book books[3] = {
{"C++ 教程","Runoob",51.50},
{"Python 教程","GuidoVanRossum",39.90},
{"人人都是量化师","fzs",42.25},
};
for(int i=0;i<3;i++){
cout << "书名:" << books[i].title << " 作者:" << books[i].author << " 价格:" << books[i].price << endl;
}
return 0;
}
运行结果:
说明:
1.struct 用来给C++用户,自定义他自己的数据结构,类型为:
struct Book{
char title[50];
char author[50];
double price;
int bookId;
} book; // 最后一个book是变量名,这是可选的,不一定要有。2.printBook(struct Book book),这个方法中,将结构体作为参数。
3. char型的变量,这里要指定长度,比如char title[50],赋值时要通过strcpy来赋值,不然会报错:error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]