C++专用函数-不在此范围内错误
C++ Private Function - Not In This Scope Error
我对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。
谢谢你的帮助。
checkIfProperID
是RunDatabase
的一个方法。这意味着您需要有一个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();
}
相关文章:
- 错误:未在此范围内声明'reverse'
- 错误:"imread"未在此范围内声明
- 我在范围内未声明的错误类有问题
- 未在此范围内声明错误 'xy'
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 错误:'[' 之前预期的非限定 id 和错误:'users'未在此范围内声明
- 在此范围内未声明错误"Clreol"
- C++ 中的类之间的数据重新循环 - 错误:'<class name>'未在此范围内声明
- 代码作为 C 文件工作,但不作为C++文件,错误:'__builtin_types_compatible_p'未在此范围内声明
- 如何修复范围内的字符串声明错误
- 如何修复错误:"vreinterpretq_u32_f64"未在此范围内声明 - 在Android上使用Eigen构建
- 如何修复C++中的"arrStud未在此范围内声明"错误
- 错误:"SHGetKnownFolderPath"未在此范围内声明
- 错误:'Sprite'未在此范围内声明
- I2C 错误:"i2c_smbus_read_byte_data"未在此范围内声明
- 如何修复错误,迭代器未在此范围内声明,并且迭代器未命名类型'
- 错误:在此范围内未声明“ numeric_limits”
- 错误:未在此范围内声明'pow'
- 为什么我会收到此错误:未在此范围内声明
- C++专用函数-不在此范围内错误