C ++编译器错误:'未在此范围内声明'

时间:2015-09-26 13:42:36

标签: c++ compiler-errors

我的计划会检查有多少学生通过/未通过考试。

我以为我之前已经声明了i,但编译器仍然显示以下错误:

 "[Error] 'i' was not declared in this scope"

此外,l.checkPass(i)中包含grade_test.cpp的行标记为红色,如果我将其更改为:l.checkPass(int i),编译器会说:

 [Error] expected primary-expression before 'int'  

这是我的代码:

grade.h

class Grade
{
    int mid_term, final;
    int total;  

    public:
        int i;
        Grade *next;
        Grade();
        Grade(int i_mid_term, int i_final, int i_total);
        void readFile(string _file);
        void printList();
        void subString(string s);
        int Show();
        void addTail(Grade *q);
        int checkPass(int i);
};

#endif

grade.cpp

int Grade::Show()
    {
        cout << mid_term << "-" << final << "-" << total << endl;
        if (mid_term < 4 || final < 4 || total < 10)
        {
            cout << "fail" << endl;
            i = i;
        }
        else 
        {
            cout << "pass" << endl;
            i++;
        }
        return i;
    }

int Grade::checkPass(int i)
    {
        cout << i << " student passed." << endl;
        cout << 6-i << " student failed." << endl; 
    } 

grade_test.cpp

int main()
{
    Grade l;
    l.readFile("mark.txt");
    l.printList(); 
    l.checkPass(i); 
    system("pause");
    return 0;
}

问题:

可能是错误的原因是什么?

2 个答案:

答案 0 :(得分:0)

您不应将i作为Grade::checkPass()的参数。

尝试更改这样的文件:

grade.h

class Grade
{
    int mid_term, final;
    int total;  

    public:
        int i;
        Grade *next;
        Grade();
        Grade(int i_mid_term, int i_final, int i_total);
        void readFile(string _file);
        void printList();
        void subString(string s);
        int Show();
        void addTail(Grade *q);
        int checkPass(); // remove "int i"
};

#endif

grade.cpp

int Grade::Show()
    {
        cout << mid_term << "-" << final << "-" << total << endl;
        if (mid_term < 4 || final < 4 || total < 10)
        {
            cout << "fail" << endl;
            // i = i; // not harmful but do nothing
        }
        else 
        {
            cout << "pass" << endl;
            i++;
        }
        return i;
    }

int Grade::checkPass() // remove "int i" so that it will see the member variable i
    {
        cout << i << " student passed." << endl;
        cout << 6-i << " student failed." << endl; 
    } 

grade_test.cpp

int main()
{
    Grade l;
    l.readFile("mark.txt");
    l.printList(); 
    l.checkPass();  // remove "i"
    system("pause");
    return 0;
}

答案 1 :(得分:0)

在你的主要内容中,你没有任何变量我声明这就是你的编译器给你错误的原因。

int Grade::checkPass(int i)
{
    cout << i << " student passed." << endl;
    cout << 6-i << " student failed." << endl; 
} 

int i将与您在课堂上声明的公共变量冲突。