无法编译C++构造函数

can not compile C++ constructor

本文关键字:构造函数 C++ 编译      更新时间:2023-10-16

谁能向我解释这段代码有什么问题以及如何修复它?这是一个更大项目的一部分,如果您需要更多信息以便提供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被创建,然后立即消失在范围之外。