C ++类可以通过引用传递给自己吗?

时间:2014-04-07 23:42:19

标签: c++ reference

尝试将父类对象传递给子类对象,以便子类对象可以控制父类对象的方法。

然而,这会导致与标题相关的问题。 我已经尝试过声明其中一个类,但似乎首先声明的类总是无法从下面声明的类中读取。

这两个错误都引用了Device'构造函数,试图调用dm的hello world方法,它们是:

Use of undefined type 'DeviceManager'
Left of '->HelloWorld' must point to class/struct/union/generic type

...

//main.cpp
#include "parent.h"

void main()
{
    cout << "Created DeviceManager\n";
    DeviceManager* deviceManager = 0;
    deviceManager = new DeviceManager;

    cout << "Giving  DeviceManager a device\n";
    deviceManager->p = new Device(deviceManager);

    cout << "Giving  Device a reference to DevicenManager\n";
    deviceManager->Share();
}

...

class DeviceManager;
class Device
{
public:
    Device(DeviceManager* manager)
    {
              dm = 0;
        this->dm = manager;
        this->dm->HelloWorld();
    }

    DeviceManager* dm;
};

//device manager
class DeviceManager
{
public:
    DeviceManager()
    {
        p = 0;
    }
    void HelloWorld()
    {
        //if this calls we know the child has control over the parent.
        cout << "Hello World";
    }

    Device* p;
};

2 个答案:

答案 0 :(得分:5)

要使用类成员和函数声明来解决循环依赖关系,可以转发声明一个类:

class A;

class B {
        A *a;
};

class A {
        B *b;
};

要定义访问其他类成员的类成员函数,必须在定义另一个类后定义函数

class B;

class A {
public:
        void f(B &arg);
};

class B {
public:
        void g(A &arg);
};

void A::f(B &arg) {
        arg.g(*this);
}

void B::g(A &arg) {
        arg.f(*this);
}

通常,在C++项目中,您甚至不会遇到此问题:您可以将函数定义(即实现)放入.cpp文件中,同时将类定义放入头文件中。如果需要,可以将类前向声明​​放入它们自己的头文件中,这些头文件包含在所有需要它们的头文件中。

如何将上述代码拆分为多个文件的完整示例:

<强> a.cpp

#include "a.h"

#include "b.h"

void A::f(B &arg) {
    arg.g(*this);
}

<强> b.cpp

#include "b.h"

#include "a.h"

void B::g(A &arg) {
    arg.f(*this);
}

<强> A.H

#ifndef _A_H_
#define _A_H_

#include "forward_declarations.h"

class A {
public:
    void f(B &arg);
};

#endif //_A_H_

<强> b.h

#ifndef _B_H_
#define _B_H_

#include "forward_declarations.h"

class B {
public:
    void g(A &arg);
};

#endif //_B_H_

<强> forward_declarations.h

#ifndef _FORWARD_DECLARATIONS_H_
#define _FORWARD_DECLARATIONS_H_

class A;
class B;

#endif //_FORWARD_DECLARATIONS_H_

作为一般的经验法则,如果你需要向前声明一个类,你可能会错误地设计一些东西并且应该考虑是否有更好的方法(但是也有完全有效的用例需要类前向声明​​)

如果您不理解我的#ifndef#define#endif预处理器行:这些是标题保护,而应该与<强>所有文件包含在其他地方,您知道正好您正在做的事情。相信我。你会后悔忘记一个。

答案 1 :(得分:1)

如果您的问题是循环依赖,请执行以下操作:

// DeviceManager.h
#include "device.h"
class DeviceManager
{
    DeviceManager(Device& device) {}
};

// Device.h
#include "DeviceManager.h"
class Device
{
    Device(DeviceManager& manager) {}
};

你可以解决问题,转发声明其中一个类,并通过指针传递对象。

// Device.h
//#include "DeviceManager.h"
class DeviceManager;
class Device
{
    Device(DeviceManager* manager) {}
};