C ++结构,在CPP文件中实现并在另一个类中使用

时间:2013-04-03 08:45:27

标签: c++ struct

在一个类中创建结构的最佳方法是什么,在那里实现并在另一个类中使用?

Structs.h

struct White{
   unsigned char r;
   unsigned char g;
   unsigned char b;
   Color() : r(255), g(255), b(255){}
};
struct Black{
   unsigned char r;
   unsigned char g;
   unsigned char b;
   Color() : r(0), g(0), b(0){}
};
White white; //works fine

Black black = {255, 255, 255}; //*error: data member initializer is not allowed!* (because of unsigned char maybe?)
**OR**
Black black; black.r = 255; //*error: this declaration has no storage class or type specifier!*

anotherClass.cpp

#include "Structs.h"
Structs *str = new Structs();
str->white.r //works, is 255
str->black.r //should be 255 too

3 个答案:

答案 0 :(得分:3)

你的设计对我来说错了。您将“黑色”和“白色”定义为不同的类,其对象具有RGB值。然后你想要一个具有白色值/属性的“黑色”?这听起来像定义一辆汽车,扯下车轮,给它翅膀和320个座位,并假装波音757仍然是一辆汽车。

您通常需要的内容如下:

struct Color {
  unsigned char r;
  unsigned char g;
  unsigned char b;
};

Color black = {0,0,0};
Color white = {255,255,255};
Color blue = {0,0,255};

答案 1 :(得分:0)

也许我不理解这个问题,但我会说演员应该是White():...和Black():...否则你的标题将无法编译。

答案 2 :(得分:0)

问题在于构造函数应该与struct_name相同。

尝试

struct White{
   unsigned char r;
   unsigned char g;
   unsigned char b;
   White() : r(255), g(255), b(255){}
   void show(void)
   {
        cout << "RED:       " << r
             << "\tGreen:   " << g
             << "\tBlack:   " << b << endl;
   }
} white;

struct Black{
   unsigned char r;
   unsigned char g;
   unsigned char b;
   Black() : r(0), g(0), b(0){}
   void show(void)
   {
        cout << "RED:       " << r
             << "\tGreen:   " << g
             << "\tBlack:   " << b << endl;
   }
} black;

black.show();
white.show();