如何在另一个类的构造函数中传递不相关的类?

时间:2018-09-27 17:23:05

标签: c++

额外的代码行只能添加到出现“ >>”符号的位置。 我的目标输入和输出如下:

输入: 15

输出: 16:15:17:16:

我仅需要

cout << r.get() << ":"; 

部分。一个解释会有所帮助。

#include <iostream>
using namespace std;

        class A {
            int i;
            public:
                A(int ai) : i(ai) {}
                int get() const { return i; }
                void update() { ++i; }
        };

        class B { 
            int i;
            public:
                B(int ai) : i(ai) {}
                int get() const { return i; }
    //>>
    operator A() {return A(i);}
    void update() { ++i; }
    }; // End of class B

    int main() {
        int i;
        cin >> i;

        A a(i++);
        B b(i);

        const B &r = static_cast<B>(a);
        a.update();
        cout << a.get() << ":";
        cout << r.get() << ":";

        const A &s = static_cast<A>(b);
        b.update();
        cout << b.get() << ":";
        cout << s.get() << ":";

        return 0;
    }

1 个答案:

答案 0 :(得分:2)

您无法通过修改类B中的转换运算符来解决提问者的问题。 B的转换运算符仅告诉构造函数如何从B生成另一个数据类型。要使用转换运算符执行此操作,该运算符必须位于类A中。

class B; // forward declaration of B so that A knows it exists

class A
{
    int i;
public:
    A(int ai) :
            i(ai)
    {
    }
    int get() const
    {
        return i;
    }
    void update()
    {
        ++i;
    }
    operator B(); // cannot implement the function yet because we do not have a 
                  // complete definition of B. Without a definition of B we cannot 
                  // construct B excluding forward defined helper functions that are 
                  // implemented later, gaining us nothing.
};

然后在B被完全定义之后,

A::operator B()
{
    return B(i); // now we have enough information to construct a B
}

注意:我们可以通过将B的定义移到A的定义之前来减少这种混乱。不幸的是,这使得支持

所需的代码成为可能。
const A &s = static_cast<A>(b);
代码后面的

要求A的正向声明,以及B定义之外的AB转换操作符的实现。

另一种选择是向B添加一个使用A

的构造函数
B::B(const A& a): i(a.get())
{

}

,反之亦然,A

相关问题