无法编译C ++构造函数

时间:2012-05-08 23:18:47

标签: c++ constructor

任何人都可以向我解释这段代码有什么问题以及如何修复它? 这是一个更大的项目的一部分,如果你需要更多的信息,以提供anwer请告诉我。

我得到的错误是这样的:

  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();

        }

3 个答案:

答案 0 :(得分:12)

在这一行:

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 除了宏

答案 1 :(得分:2)

因为你已经注释了这一行

if(!input.good())
    //return 1;

字符串callnumber仅在该范围内声明,并且在其外部不可用。

删除if语句或取消注释返回行

答案 2 :(得分:1)

        if(!input.good())
            //return 1;
        string callnumber;

实际上是

        if(!input.good()) {
            //return 1;
            string callnumber;
        }

因为注释掉的//return 1;不是声明。因此callnumber被创建,然后立即消失在范围之外。

相关问题