无法编译C++构造函数
can not compile C++ constructor
谁能向我解释这段代码有什么问题以及如何修复它?这是一个更大项目的一部分,如果您需要更多信息以便提供ANWER,请告诉我。
IM得到的错误是这样的:
g++ -c search.cpp
search.cpp: In constructor ‘Search::Search()’:
search.cpp:26:26: error: ‘callnumber’ was not declared in this scope
make: *** [search.o] Error 1
Search::Search()
{
ifstream input;
input.open("data.txt", ios::in);
if(!input.good())
//return 1;
string callnumber;
string title;
string subject;
string author;
string description;
string publisher;
string city;
string year;
string series;
string notes;
while(! getline(input, callnumber, '|').eof())
{
getline(input, title, '|');
getline(input, subject, '|');
getline(input, author, '|');
getline(input, description, '|');
getline(input, publisher, '|');
getline(input, city, '|');
getline(input, year, '|');
getline(input, series, '|');
getline(input, notes, '|');
Book *book = new Book(callnumber, title, subject, author, description, publisher, city, year, series, notes);
Add(book);
}
input.close();
}
在这一行:
if(!input.good())
//return 1;
string callnumber;
您用分号注释掉了该行,并且没有使用大括号,并且当涉及到标记之间的空格和换行符 1 时,C++对空格不敏感,因此通过删除注释(并添加缩进)我们可以看到它相当于
if (!input.good())
string callnumber;
我们可以看到callnumber
的声明是if
本地的。添加大括号或分号以使callnumber
声明位于if
之外(或将其完全删除):
if (!input.good()) { // or ;
//return 1;
}
string callnumber;
<小时 />1 宏除外
因为你已经评论了这一行
if(!input.good())
//return 1;
字符串调用号仅在该作用域内声明,在作用域外不可用。
也删除 if 语句或取消注释返回行
if(!input.good())
//return 1;
string callnumber;
是有效的
if(!input.good()) {
//return 1;
string callnumber;
}
因为注释掉的//return 1;
不是语句。 因此,callnumber
被创建,然后立即消失在范围之外。
相关文章:
- "error: no matching function for call to"构造函数错误
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 选择要调用的构造函数
- 如何委托派生类使用其父构造函数?
- 构造函数正在调用一个使用当前类类型的函数
- 没有用于初始化C++中的变量模板的匹配构造函数
- 初始化具有非默认构造函数的std::数组项的更好方法
- 当从函数参数中的临时值调用复制构造函数时
- 在c++构造函数中使用随机字符串生成器
- 一对向量构造函数:初始值设定项列表与显式构造
- 从构造函数抛出异常时如何克服内存泄漏
- 我不明白为什么我声明一个空的内部结构并将其传递给构造函数
- 继承:构造函数,初始化C++11中基类的类C数组成员
- 具有默认模板类型的默认构造函数的类型推导
- 使用dynamic_cast和构造函数时出错
- 在c++中使用向量时,如何调用构造函数和析构函数
- 奇怪的构造函数行为