0

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

结构体.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!*

另一个类.cpp

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

3 回答 3

3

你的设计在我看来是错误的。您将“Black”和“White”定义为不同的类,其对象具有 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};
于 2013-04-03T08:58:09.057 回答
0

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

于 2013-04-03T08:52:22.400 回答
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();
于 2013-04-03T09:04:03.753 回答