C++专用函数-不在此范围内错误

C++ Private Function - Not In This Scope Error

本文关键字:范围内 错误 专用 函数 C++      更新时间:2023-10-16

我对C++非常陌生,来自Java和C。我的书中没有提到私有函数,谷歌搜索也没有出现太多。这对我来说应该是微不足道的,但我无法让它发挥作用。

我有这个代码:

#ifndef RUNDATABASE_H
#define RUNDATABASE_H
#include <iostream>
#include <string>
class RunDatabase
{
    public:
        int main();
    protected:
    private:
        bool checkIfProperID(std::string);
};
#endif // RUNDATABASE_H

在另一个文件中:

#include "RunDatabase.h"
int main()
{
    std::string id; // after this, I initialize id
    if(!checkIfProperID(id))
    {
        std::cout << "Improperly formatted student ID, must be numeric" << std::endl;
        break;
    }
}
bool RunDatabase::checkIfProperID(std::string id)
{
    return true;
}

我得到这个错误:error: 'checkIfProperID' was not declared in this scope

在Windows 7 64位上使用MinGW g++4.4.1。

谢谢你的帮助。

checkIfProperIDRunDatabase的一个方法。这意味着您需要有一个RunDatabase对象才能调用checkIfProperID

RunDatabase rd;
rd.checkIfProperID(id);

我不明白为什么其他函数不在范围内。

这里的"范围"是类。

RunDatabase::checkIfProperID

请注意作用域解析操作符::。这意味着该方法属于类,而不是全局范围。

与Java不同,C++允许独立的函数。运行程序时调用的main函数是独立的main,而不是成员main。如果您按照以下方式修改您的cpp文件,则应该编译:

int main() {
    RunDatabase rdb;
    rdb.main();
}
RunDatabase::main() {
    // the code of the main function from your post
}

问题是main未作为RunDatabase的成员实现。

int main()
{

应该是

int RunDatabase::main()
{

然后,您将需要一个main()函数,您的程序将在中开始执行该函数

还要考虑不要在开始执行的主函数之后命名类成员函数,以避免混淆。示例:

class RunDatabase
{
public:
    int execute();
protected:
private:
    bool checkIfProperID(std::string); 
};
int RunDatabase::execute()
{
    std::string id; // after this, I initialize id
    if(!checkIfProperID(id))
    { 
        std::cout << "Improperly formatted student ID, must be numeric" << std::endl;
        break;
    }
}
/// runs when the program starts
int main()
{
    RunDatabase runDatabase;
    runDatabase.execute();
}