C ++相互依赖的类

时间:2015-06-03 03:45:08

标签: c++

我有两个类,它们代表两种可以来回转换的不同数据类型。我希望每个都有一个构造函数,它接受另一个类型的对象,这样我就可以更容易地在两者之间进行转换,如下所示:

class A{
 public:
  A(B n){
    //Do stuff converting n to type A
  }
};

class B{
 public:
  B(A n){
    //Do stuff converting n to type B
  }
};

但总是无法编译。

2 个答案:

答案 0 :(得分:3)

如果您通过引用传递extractFile,则可以在B中将其用作不完整类型,并带有前向声明,例如:

A

请注意,您还需要至少class B; // forward declaration class A { public: A() = default; A(B& n); // declare it here }; class B { public: B() = default; B(A n) { //Do stuff converting n to type B } }; A::A(B& n) // define it here, B is fully visible now { //Do stuff converting n to type A } int main() { A a; B b(a); A another(b); } A的默认构造函数,否则您无法创建B而没有A或其他方式。我们也只在B中声明了构造函数,但在A完全可见后定义了它(感谢@MattMcNabb的注释)。这样,您就可以在构造函数中使用B的任何成员,因为此时B完全可见。

答案 1 :(得分:1)

你遇到的问题对于C ++的初学者来说很常见(或者C就此而言)。

问题是,在看到A(B n)的声明之前,编译器会看到签名B。但显然,您无法在B之前将A放在代码中,或者您最终会遇到相同类型的情况。

这可以使用前向声明和引用来解决。我建议的默认方法是将这两个实体声明为

class B;

class A {
 public:
  A(const B& n) {
    // Do stuff converting n to type A
  }
};

class B {
 public:
  B(const A& n) {
    // Do stuff converting n to type B
  }
};
相关问题