简体   繁体   English

另一个类成员函数中另一个类的对象

[英]Object of another class in another class member function

I have following code: 我有以下代码:

class A
{
public:
    A();

private:
    void slot();
};

The second class B looks like: 第二类B看起来像:

class B
{
public:
    B();

private:
    // Some stuff...
};

In file1.cpp there are static objects of both classes: 在file1.cpp中,两个类都有静态对象:

static A a;
static B b;

Now in file2.cpp(containing the class implementation) I would need in the slot function of class A the object b , which was created in file1.cpp. 现在在file2.cpp(包含类实现)中,我将在class A的slot函数中需要对象b ,它是在file1.cpp中创建的。 What is the best way to get it? 最好的方法是什么? How is this done using C++? 如何使用C ++完成?

static means "local to this translation unit". static表示“本地于此翻译单元”。 What you are trying to do is impossible. 您试图做的事是不可能的。

An alternative design would use non-static namespace scope objects, like: 另一种设计将使用非静态名称空间作用域对象,例如:

globals.hpp: globals.hpp:

extern A a;
extern B b;

globals.cpp: globals.cpp:

#include "globals.hpp"
A a;
B b;

A.cpp: A.cpp:

#include "globals.hpp"
void A::slot(){
    //use b
}

You need to be careful with this design to ensure that you do not call A::slot before b has been constructed. 您需要谨慎使用此设计,以确保在构造b之前不要调用A::slot

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM