首页 > 解决方案 > main() 中定义的类对象。如何在另一个类中获取此实例?

问题描述

我需要将functionA作为函数 B 中的全局函数,只使用 main() 中定义的类 A 的一个实例。functionA将在许多类中使用,我希望尽可能简单地访问。我知道在 .h 文件中定义类是一种不好的做法,但我认为在这种情况下它并不重要。在我的情况下,我得到了错误,但我怎样才能以同样的方式做到这一点?如果我在此A a();之前放置main()完美,但 A 在main()函数中被初始化。

/////A.h//////
class A
{
public:
    A(){//define constructor A//};
    functionA()
    {
        ...
    }
};
/////B.h//////
extern A a; //declare A//
class B
{
public:
    B(){//define constructor B//};
    functionB()
    {
        a.functionA();
    }
};
////main.cpp////

#include "A.h"
#include "B.h"
int main()
{
    B b(); //B b; 
    A a(); //A a; of course. Thanks for remark guys.
}

这是我得到的错误:

Error LNK2001: unresolved external symbol "class A a" 

标签: c++classheaderlinker-errors

解决方案


推荐阅读