【问题标题】:"Not declared in scope" C++ issue“未在范围内声明”C++ 问题
【发布时间】:2012-06-28 10:41:29
【问题描述】:

我正在用 C++ 为一个班级(学校,而不是代码)编写一个简单的班级。我有一点 C++ 经验,但是已经有一段时间了,所以我正在重新学习我忘记的东西并学习了很多新语法(我在 Java 方面有更多经验)。代码如下:

#include <iostream>
#include <string>

using namespace std;
class Project112
{
private:
    string romanNumeral;
    int decimalForm;
public:
    Project112()
    {
        romanNumeral = "";      
        decimalForm = 0;
    }
    int getDecimal()
    {
        return decimalForm;
    }
};

这是驱动程序:

include cstdlib
include <iostream>

using namespace std;
int main() 
{
    Project112 x;
    int value2 = x.getDecimal();
    return 0;
}

这是一个更大程序的一部分,但我已将其简化为这个,因为这是问题所在。每次我尝试运行程序时,都会出现以下错误:

main.cpp:10: error: 'Project112' was not declared in this scope
main.cpp:10: error: expected `;' before 'x'
main.cpp:14: error: 'x' was not declared in this scope

有人可以解释一下这个问题吗?提前致谢。

【问题讨论】:

  • 您似乎没有包含您的班级标题。不过,您可以减少代码,这对您有好处。您应该做的一件事(谁知道呢,老师可能也更喜欢它!)是丢失污染全局命名空间的 using namespace std; 语句。

标签: c++ oop scope


【解决方案1】:
#include "Project112.h"

在 main 上方添加。您忘记包含头文件。并且:

using namespace std;

不要在头文件中这样做。这会将 std 命名空间中的所有内容导入到包含您的标头的任何文件的全局命名空间中。只需完全限定标头中的类型,即std::string,我会在大型项目中的实现文件中避免这种情况(尽管在实现文件中像using std::string 这样的IMO 是可以的)。

【讨论】:

    猜你喜欢
    • 2016-04-14
    • 2010-12-17
    • 1970-01-01
    • 2022-01-21
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2015-08-21
    相关资源
    最近更新 更多