我是 C++ 的新手,来自 Java 和 C。我的书没有提到私有(private)函数,谷歌搜索也没有出现太多。这对我来说应该是微不足道的,但我无法让它发挥作用。
我有这个代码:
#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。
感谢您的帮助。
最佳答案
checkIfProperID
是RunDatabase
的一个方法。这意味着您需要有一个 RunDatabase
对象才能调用 checkIfProperID
。
RunDatabase rd;
rd.checkIfProperID(id);
I don't see why the other function is not in the scope.
这里的“范围”是类。
RunDatabase::checkIfProperID
注意作用域解析运算符 ::
。这意味着该方法属于类,而不是全局范围。
关于C++ 私有(private)函数 - 不在此范围内错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9594842/