0

好吧,这个问题的正确标题应该是“类的循环依赖,实例可以从另一个初始化”。

我有两个类(带有整数数据字段的 Index3i 和带有浮点数据字段的 Index3f)意味着可以“转换”到另一个类,反之亦然:

文件“Index3i.h”:

// #include "Index3f.h"

class Index3i {
public:
    Index3i()
    : r(0), g(0), b(0) { }

    Index3i(const Index3i& copy)
    : r(copy.r), g(copy.g), b(copy.b) { }

    // Index3i(const Index3f& copy)
    // : r((int)copy.r), g((int)copy.g), b((int)copy.b) { }

    // Index3f toIndex3f() { ... }

    ...
};

文件“Index3f.h”:

// #include "Index3i.h"

class Index3f {
public:
    Index3f()
    : r(0.0f), g(0.0f), b(0.0f) { }

    Index3f(const Index3f& copy)
    : r(copy.r), g(copy.g), b(copy.b) { }

    // Index3f(const Index3i& copy)
    // : r((float)copy.r), g((float)copy.g), b((float)copy.b) { }

    // Index3i toIndex3i() { ... }

    ...
};

我需要Index3i类对象能够初始化并转换为Index3f类对象,反之亦然。另外,我只想保留这些类的标题

好吧,如果我尝试取消注释已注释的构造函数、方法和包含,则会产生循环依赖问题。另一种可能的解决方案是实现一些转换函数并将它们放在第三个包含文件中,如“IndexConvert.h”左右。

但也许还有其他方法?你能建议我为这个案子提供一个合适的解决方案吗?

4

1 回答 1

2

使它们都成为单个类模板-听起来您实际上不需要从两个不同的类开始。这样,您只需编写一个转换构造函数模板:

template <class T>
class Index3 {
    T r, g, b;

public:
    Index3() : r(0), g(0), b(0) { }
    Index3(const Index3&) = default;

    template <class U, class = std::enable_if_t<std::is_convertible<U, T>::value>>
    Index3(const Index3<U>& rhs)
    : r(rhs.r), g(rhs.g), b(rhs.b)
    { }

    /* rest */
};
于 2016-03-19T13:08:44.670 回答