【问题标题】:not declared in scope, even though declared in .h未在范围内声明,即使在 .h 中声明
【发布时间】:2012-06-05 15:34:48
【问题描述】:

我一直坚持这个,我的老师甚至不知道发生了什么。如果有人可以帮助我,将不胜感激。

我已经在 Line 结构的头文件中声明了 item。但是,在 Line::display() 方法中调用它时,我收到一条错误消息,指出该变量未在范围内声明。我已经向我的老师和同龄人展示过,但似乎没有人知道解决方案。

这是我的 .h:

//Line.h
#define MAX_CHARS 40
struct Line {
    public:
    bool set(int n, const char* str);
    void display() const;

    private:
    char item[MAX_CHARS];
    int no;
    };

这是我的 .cpp 文件。

// Line.cpp
#include "Line.h"
#include <iostream>
using namespace std;

#define MAX_CHARS 40

void Line::display() const {
    cout << no << ' ' << item << endl;
}

对此的任何帮助都很棒。提前致谢。

【问题讨论】:

  • 您使用的是什么编译器/平台?
  • 等你说当你调用它时你会得到错误?不是你编译的时候?

标签: c++ header struct scope


【解决方案1】:

如果这是您的实际代码,您可能是从其他地方获取标题。试试:

#include "C:\\fullPathToHeader\\Line.h"
#include <iostream>
using namespace std;

void Line::display() const {
    cout << no << ' ' << item << endl;
}

还有:

  • 不要在cpp 文件中重新定义MAX_CHARS
  • 对标头使用包含防护。

【讨论】:

    【解决方案2】:

    要使 Line::display const 意味着您不需要实例变量数据。

    // Line.cpp
    #include "Line.h"
    #include <iostream>
    using namespace std;
    
    void Line::display()
    {
        cout << no << ' ' << Line::item << endl;
    }
    

    【讨论】:

    • 不,这意味着您不会更改实例成员。
    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 2011-09-14
    • 2016-08-09
    相关资源
    最近更新 更多