枚举“复制”问题
我有一个类,我们称之为 A。它有一个枚举 (E) 和一个方法 Foo(E e),参数中包含 E。我想为 A 编写一个包装器(装饰器)W。因此它将有自己的方法 Foo(A::E)。但我想要某种封装,所以这个方法应该定义为 Foo(F f),其中 F 是 W 中定义的另一个枚举,可以转换为 A::E。例如:
class A
{
public:
enum E { ONE, TWO, THREE };
void Foo(E e);
};
class B
{
//enum F; // ???
void Foo(F f)
{
a_.Foo(f);
}
private:
A a_;
};
F应该如何定义?我不想复制这样的值:
enum F { ONE = A::ONE, TWO = A::TWO, THREE = A::THREE };
因为它是附近功能中的潜在错误。 typedef 定义是:
typedef A::E F;
是最好的决定吗?合法吗?
I have a class, let's call it A. It has a enum (E) and a method Foo(E e), with gets E in the arguments. I want to write a wrapper (decorator) W for A. So it'll have its own method Foo(A::E). But I want to have some kind of encapsulation, so this method should defined as Foo(F f), where F is another enum defined in W, that can be converted to A::E. For example:
class A
{
public:
enum E { ONE, TWO, THREE };
void Foo(E e);
};
class B
{
//enum F; // ???
void Foo(F f)
{
a_.Foo(f);
}
private:
A a_;
};
How F should be defined? I don't want to copy value like this:
enum F { ONE = A::ONE, TWO = A::TWO, THREE = A::THREE };
because its a potential error in the near feature. Is the typedef definition:
typedef A::E F;
is the best decision? Is it legal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
typedef 的问题是它不会让 A 消失。您不能说
F f = B::ONE;
,因为 B::ONE 不存在。您仍然必须使用 A::ONE 等。据我了解,这不是您想要的。对于您想要的东西,在 B 中创建一个新的枚举可能是您最好的选择。这里唯一需要注意的是 1) 您需要在 A::E 和 B::F 之间进行类型转换,2) 一个枚举中的更改需要反映在另一个枚举中。
不过,没有必要按照您的方式复制这些值。如果 A::E 是:
然后您可以复制并粘贴它来创建 B::F:
但是,这种复制和粘贴的缺点是:粘贴的是,如果我决定将 A::TWO 更改为等于 10,我必须确保更改 B::TWO。如果您按照所示方式定义 B::F ( ONE = A::ONE ... ),这不会是问题,但会多做一点工作。
The problem with the typedef is that it doesn't make A go away. You wouldn't be able to say
F f = B::ONE;
, because B::ONE wouldn't exist. You'd still have to use A::ONE, etc. From what I understand, that's not what you want.For what it seems like you're going for, creating a new enumeration in B is probably your best bet. The only things to beware of here are 1) you will need to type cast between A::E and B::F and 2) changes in one enumeration need to be mirrored in the other.
It wouldn't be necessary to copy the values the way you do, though. If A::E was:
You could then copy and paste this to create B::F:
However, the disadvantage of this copy & paste is that if I then decide to change A::TWO to be equal to ten, I would have to be sure to change B::TWO. If you defined B::F the way you showed ( ONE = A::ONE ... ), this wouldn't be a problem but it would be little bit more work.
我认为为了增强程序的简单性,您提供的两个选择中更好的一个是使用 typedef ,除非有一些令人信服的理由不这样做。我当然不建议重复功能(正如您的第一种方法似乎正在做的那样),因为这很快就会成为维护问题。
I think in order to enhance your program's simplicity, the better of the two choices you presented is to go with the typedef unless there's some compelling reason not to. I certainly don't recommend duplicating functionality (as your first approach seems to be doing) as that rapidly becomes a maintenance concern.