无法使用 c++ 中的构造函数初始化对象

Can`t initialize object using constructor in c++

本文关键字:构造函数 初始化 对象 c++      更新时间:2023-10-16
   #include <iostream>
using namespace std;
class Book
{
public:
Book(const string& ISBN,const string& title,const string& author,const string& cprDate,const bool& ch);
void checkBook(void);
void uncheckBook(void);
string ISBN(){return I;};
string title(){return t;};
string author(){return a;};
string cprDate(){return c;};
bool isChecked(){return check;};
private:
string I;   //ISBN
string t;   //title
string a;   //author
string c;   //copyright date
bool check; //is checked?
};
Book::Book(const string& ISBN,const string& title,const string& author,const string& cprDate,const bool& ch){
I=ISBN;
t=title;
a=author;
c=cprDate;
check=ch;
}
void Book::checkBook(void)
{
check=true;
}
void Book::uncheckBook(void)
{
check=false;
}
int main()
{
Book eragon{"ISBN:19851654-1851651-156115-156156","Eragonas","Paolini","2007",true};
//^This does not compile, it gives 2 errors: expected primary-expression before eragon
//and expected ';' before semicolon
return 0;
}

我正在做"编程 - 使用C++的原则和实践"一书中的练习,我被困在第9章练习5

本练习和接下来的几个练习要求您设计和实现 Book 类,例如您可以想象为库软件的一部分。类书应具有 ISBN、标题、作者和版权日期的成员。同时存储有关图书是否已签出的数据。创建用于返回这些数据值的函数。创建用于签入和签出书籍的函数。对输入到书中的数据进行简单的验证;例如,仅接受 nn-n-x 格式的 ISBN,其中 n 是整数,x 是数字或字母。将 ISBN 存储为字符串。

我什至无法初始化书籍对象:/

编译器未处于 C++11 模式。{...}初始值设定项语法是 C++11 中的新增语法。请参阅此问题,了解如何在 CodeBlock 中启用 C++11 支持。

另一种选择是使用 C++03 语法,但如果本书使用的是 C++11,您最终可能需要打开它。C++03 语法为:

Book eragon("ISBN:19851654-1851651-156115-156156","Eragonas","Paolini","2007",true);
我不知道

你的编译器是否在为你做这件事,但是,可能需要包含字符串头

 #include <string>

并且,正如 Dark Falcon 所说,将你的书初始化从 {...} 更改为 (...(,以便在编译器 pre c++11 中进行编译

在 int main(( 中,您使用错误的括号集初始化构造函数。使用 (( 代替 {}。

将其更改为-

书埃拉贡("ISBN:19851654-1851651-156115-156156","埃拉贡纳斯","保里尼","2007",真(;

希望它能解决您的问题。

在经典C++中,您可以使用以下方法在堆上分配一本书

    Book *eragon = new Book("ISBN: ..." And all your other parameters 

我在平板电脑上,无法复制您的所有参数以准确显示