令牌之前声明中的限定 ID '('

qualified-id in declaration before '(' token

本文关键字:ID 声明 令牌      更新时间:2023-10-16

这是一个疯狂的错误,给我带来了很多麻烦。

#include <iostream>
using namespace std;
class Book {
private:
    int bookid;
    char bookname[50];
    char authorname[50];
    float cost;
public:
    void getinfo(void) {
        for (int i = 0; i < 5; i++) {
            cout << "Enter Book ID" <<endl;
            cin >> bookid;
            cout << "Enter Book Name" << endl;
            cin >> bookname;
            cout << "Enter Author Name" << endl;
            cin >> authorname;
            cout << "Enter Cost" << endl;
            cin >> cost;
        }
    }
    void displayinfo(void);
};

int main()
{
    Book bk[5];
    for (int i = 0; i < 5; i++) {
        bk[i].getinfo();
    }
    void Book::displayinfo() {
        for(int i = 0; i < 5; i++) {
            cout << bk[i].bookid;
            cout << bk[i].bookname;
            cout << bk[i].authorname;
            cout << bk[i].cost;
        }
    }
    return 0;
}

标题中指出的错误应该在main

中的void Book::displayinfo()行'}'标记之前声明。

将函数定义void Book::displayinfo(){}移出main()

除此之外,我还有一些建议给你。像这样更新你的类定义
class Book{
private:
  int bookid;
  string bookname; // char bookname[50]; because it can accept book name length more than 50 character. 
  string authorname; // char authorname[50]; because it can accept authorname length more than 50 character. 
  float cost;
public:
    void getinfo(void){
        for(int i =0; i < 5; i++){
            cout << "Enter Book ID" <<endl;
            cin >> bookid;
            cout << "Enter Book Name" << endl;
            getline(cin,bookname); // Because book name can have spaces.
            cout << "Enter Author Name" << endl;
            getline(cin,authorname); // Because author name can have spaces too.
            cout << "Enter Cost" << endl;
            cin >> cost;
        }
    }
    void displayinfo(void);
};