记录自己的各种报错,在错误中学习ing
结构体全局变量的声明与初始化问题
#include <iostream>
using namespace std;//声明一个结构体Books
struct Book{string name;string author;string subject;int id;//构造函数Book(string name, string author, string subject, int id):name(name), author(author), subject(subject), id(id){
}
}book1,book2;//打印
void printBookInfo(const Book& book)
{cout << "name: " << book.name << endl;cout << "author: " << book.author << endl;cout << "subject: " << book.subject << endl;cout << "ID: " << book.id << endl;
}int main()
{
book1=Book("C++ Primer", "Bjarne Stroustrup", "Programming", 101);
book2=Book("C++ Primer Plus", "Bjarne Stroustrup", "Programming", 102);printBookInfo(book1);
printBookInfo(book2);return 0;
}
这段代码主要问题在于 Book
结构体的成员变量book1
和 book2
的初始化方式上。
book1
和 book2
是在全局范围内声明的变量,并且它们是结构体类型的实例,不能直接在声明之后使用赋值操作符进行初始化。
解决方法有两种
1.
在main函数外面声明并初始化
#include <iostream>
using namespace std;// 声明一个结构体 Book
struct Book {string name;string author;string subject;int id;// 构造函数Book(string name, string author, string subject, int id) :name(name), author(author), subject(subject), id(id) {}
} book1("C++ Primer", "Bjarne Stroustrup", "Programming", 101),book2("C++ Primer Plus", "Bjarne Stroustrup", "Programming", 102);// 打印函数
void printBookInfo(const Book& book) {cout << "name: " << book.name << endl;cout << "author: " << book.author << endl;cout << "subject: " << book.subject << endl;cout << "ID: " << book.id << endl;
}int main() {// 已经在外部初始化了 book1 和 book2,直接调用打印函数即可printBookInfo(book1);printBookInfo(book2);return 0;
}
在main函数中声明变量并初始化
#include <iostream>
using namespace std;// 声明一个结构体 Book
struct Book {string name;string author;string subject;int id;// 构造函数Book(string name, string author, string subject, int id) :name(name), author(author), subject(subject), id(id) {}
};// 打印函数
void printBookInfo(const Book& book) {cout << "name: " << book.name << endl;cout << "author: " << book.author << endl;cout << "subject: " << book.subject << endl;cout << "ID: " << book.id << endl;
}int main() {// 使用构造函数初始化 book1 和 book2Book book1("C++ Primer", "Bjarne Stroustrup", "Programming", 101);Book book2("C++ Primer Plus", "Bjarne Stroustrup", "Programming", 102);// 调用打印函数printBookInfo(book1);printBookInfo(book2);return 0;
}