无法使用 c++ 中的构造函数初始化对象
Can`t initialize object using constructor in c++
#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
我在平板电脑上,无法复制您的所有参数以准确显示
相关文章:
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 如何在 C++ 中使用它的构造函数初始化 unique_ptrs 的 2D 向量?
- 在C++中使用默认构造函数初始化对象的不同方法
- 使用默认构造函数初始化对象的不同方法
- 我们可以用参数化构造函数初始化结构的数组吗?
- 有没有办法使用该类的构造函数初始化另一个类的私有部分内的对象数组?
- 类内初始化与构造函数初始化列表的顺序
- 通过 C++ 中的重载构造函数初始化未知类型的变量
- 使用复制构造函数初始化 new[]
- 如何从子类的构造函数初始化父类的私有成员
- 在构造函数初始化列表中使用 std::variant
- 使用构造函数初始化结构还是在之后设置其值更好?
- C++ 没有匹配的构造函数初始化 []
- 我正在使用dev c ++,但收到错误(C++98'array'必须由构造函数初始化)
- 使用所述填充构造函数初始化向量中的向量
- 如何同时创建一个具有两个或多个构造函数初始化的对象
- 在 new 关键字中,由默认构造函数初始化的类中的元素是否也使用 new 关键字在C++?
- 这是使用构造函数初始化数组对象的最佳方法吗?
- 内置类型的构造函数初始化
- 构造函数初始化和对象损坏