【问题标题】:(C++) Use other class' object as parameter in a class when two classes use each other's object(C++) 当两个类使用彼此的对象时,使用其他类的对象作为类中的参数
【发布时间】:2013-06-12 08:58:15
【问题描述】:

我的标题听起来有点奇怪...... 但我的问题是……

class A{
public:
    doSomething(B & b);
}

class B{
public:
    doSomething(A & a);
}

这不应该工作吗??

我收到错误消息说函数不接受 1 个参数 因为标识符(类)未定义...

【问题讨论】:

    标签: c++ class parameter-passing


    【解决方案1】:

    类型需要先声明才能使用。由于类之间存在相互依赖关系,因此需要使用前向声明。

    class B; // Forward declaration so that B can be used by reference and pointer
             // but NOT by value.
    
    class A{ public: doSomething(B & b); }
    
    class B{ public: doSomething(A & a); }
    

    请注意,这通常被认为是一个非常糟糕的设计,应尽可能避免。

    【讨论】:

    • 如何前向声明一个类??
    • 使用class CLASSNAME; 其中CLASSNAME 是您要转发声明的类的名称。
    【解决方案2】:
    class A{
    public:
        doSomething(B & b);
    };
    

    不行,因为编译器还不知道 B 是什么,这是后面定义的。

    编译器始终以自上而下的方式工作,因此它必须先看到一个类(声明或定义),然后才能在其他地方使用,因此您的代码应该是

    class A; // Not reqd in your case , but develop a good programming practice of using forward declaration in such situations
    class B; // Now class A knows there is asnothed class called B , even though it is defined much later , this is known as forward declaration
    
    class A{
    public:
        doSomething(B & b);
    }
    
    class B{
    public:
        doSomething(A & a);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多