【问题标题】:Use an object that only gets declared in the file including the original file使用仅在文件中声明的对象,包括原始文件
【发布时间】:2017-11-06 22:17:06
【问题描述】:

抱歉标题令人困惑,但我想不出更好的方式来表达我的问题。

我有一个类 Foo,它在文件 Foo.cpp 中声明。

Foo.cpp 然而,包括文件Bar.h 和类Bar 尝试创建对象Foo 的新实例。当然,我得到一个未定义的标识符错误。我需要在每个文件中包含两个标题,因为我需要从每个文件中访问一些静态成员。

有没有办法实现这个功能?

示例: Foo.h

#ifndef FOO_H
#define FOO_H

#include "Bar.h"

class Foo 
{
public:
    Foo()
    {
        _newNum = Bar::_num;
    }
private:
    int _newNum
};

Bar.h

#ifndef BAR_H
#define BAR_H

#include "Foo.h"    

class Bar
{
public:
    static int _num;

private:
    Foo f; // Error occurs here, Foo is undefined according to Foo.h.
};

编辑:AHHH 很抱歉写得很糟糕的问题。我感觉很累。固定。

【问题讨论】:

  • 类声明后缺少分号(;)?另外,您为什么将Bar.hFoo.h 包括在内,反之亦然??
  • 如果Bar是需要使用Foo的,为什么Foo包含Bar.h?这似乎只是错误的方式
  • 感谢您纠正我的错误

标签: c++ class oop object undeclared-identifier


【解决方案1】:

就您的示例而言,Foo.h 没有理由需要#include Bar.h。

修复:

#include "Foo.h"

在 Bar.h 的顶部,包含守卫的下方。

【讨论】:

  • 对于写得不好的问题,我深表歉意。我已经更新了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多