C ++在构造函数中需要两个类吗?

San*_*lin 3 c++ constructor class

我在.h文件中有两个非常相似的类,它们在构造函数中需要互相配合。它是关于Color类的,一个将使用无符号char 0到255作为RGB,另一个将使用浮点数0.0到1.0作为RGB,我需要能够在构造函数和赋值运算符以及其他成员函数中相互转换。

Color3.h:

class Color3 {
    public:
    unsigned char R, G, B;
    Color3()
    : R(0), G(0), B(0) {

    }

    Color3(unsigned char r, unsigned char g, unsigned char b)
    : R(r), G(g), B(b) {

    }

    Color3(const Color3f& other)
    : R(other.R*255), G(other.G*255), B(other.B*255) {

    }
};


class Color3f {
    public:
    float R, G, B;
    Color3f()
    : R(0), G(0), B(0) {

    }

    Color3f(float r, float g, float b)
    : R(r), G(g), B(b) {

    }

    Color3f(const Color3& other)
    : R(other.R/255), G(other.G/255), B(other.B/255) {

    }
};
Run Code Online (Sandbox Code Playgroud)

我可以将它们放在单独的文件中而不进入通函(我相信这就是所谓的)包含吗?我想我知道这个问题的答案,但我想知道那里可能还有其他解决方案。我希望它们位于同一文件中,但是如果没有其他方法,那么我将它们分开。

Fre*_*son 6

是的,如果您使用前向声明。例如:

class Color3f; // <--- Forward declaration

class Color3
{
public:
    unsigned char R, G, B;
    Color3()
        : R(0), G(0), B(0)
    {

    }
    Color3(unsigned char r, unsigned char g, unsigned char b)
        : R(r), G(g), B(b)
    {

    }

    // Can't define this yet with only an incomplete type.
    inline Color3(const Color3f& other);
};


class Color3f
{
public:
    float R, G, B;
    Color3f()
        : R(0), G(0), B(0)
    {

    }
    Color3f(float r, float g, float b)
        : R(r), G(g), B(b)
    {

    }
    Color3f(const Color3& other)
        : R(other.R/255), G(other.G/255), B(other.B/255)
    {

    }
};

// Color3f is now a complete type, so define the conversion ctor.
Color3::Color3(const Color3f& other)
        : R(other.R*255), G(other.G*255), B(other.B*255)
    {

    }
Run Code Online (Sandbox Code Playgroud)

  • ...咳嗽.. *内联* ...(如果这都在标题中)。和 +1 顺便说一句。 (2认同)