2014-02-19 107 views
2

我在.h文件中有两个非常相似的类,在构造函数中需要彼此。它是关于一个Color类的,一个将使用无符号字符0到255作为RGB,另一个将使用浮点数0.0到1.0作为RGB,并且我需要能够在构造函数和赋值运算符以及其他成员函数中从一个和另一个进行转换。C++构造函数中需要彼此的两个类?

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) { 

    } 
}; 

我可以把它们放在不同的文件,而无需进入一个圆形(我认为,这是多么称为)包括哪些内容?我想我知道这个问题的答案,但我想知道可能有哪些其他解决方案。我更喜欢他们在同一个文件中,但如果没有其他方式,我会分开他们。

+1

请编写没有明显错误的代码,如果你自己试着编译你写的内容,会更好。在你的类中,Color3f的构造函数被命名为Color3 –

+0

对不起,我修复了代码(复制粘贴从未给我带来过什么好处) –

回答

4

是的。

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) 
    { 

    } 
+0

谢谢,这是完美的:)我会在15分钟的时间内通过。 –

+1

...咳嗽.. *内联* ...(如果全部在标题中)。和+1 btw。 – WhozCraig

+0

@WhozCraig:已提示。编辑。 –

0

这些情况是'pragma once'的用途。只需将其添加到您的.h文件的顶部,它只会被包含一次:

#pragma once 

但是,请确保它只是一个“包括”环,而不是实际的功能回路。看起来你的构造函数实际上可能会导致I循环。

0

您可以将其他类的声明添加到头文件的顶部以避免循环依赖问题。例如:

class Color3; 

Color3f.h顶部,同样对于其他类。结合#pragma once#ifndef包括后卫,该程序可以与分割文件很好地编译。

但是这个类似的类应该被声明为专用不同模板参数的同一类。例如Color3<unsigned char>Color3<float>

+0

对这些类进行模板化会混淆这些方法,因为无符号字符RGB操作与float RGB操作不同。我想这样做,但这意味着我应该写无符号字符和浮点值的重载方法。 –