1

假设我们有 2 个类 A 和 B。它们都是超类 C 的子类。现在让我们假设 C 定义了一个方法 areYouA(),这是一个询问对象是否是 A 类的对象的方法。

因此,在 c++ 中,可能的代码是:

C object1 = A()

C object2 = B()

if (object1.areYouA()==true){//crazy code here regarding if it's an A object}

if (object2.areYouA()==false){//crazy code here regarding if it's a B object}

从 OO POV 向 B 和 C 类添加方法以询问它们各自的对象是否属于 A 类是否正确???如果它不正确,那么还有什么方法可以解决这个问题????我的目标很明显,我需要 2 个 A 类和 B 类,在某些时候,我有部分二进制数据可能属于 A 类或 B 类,而且一个对象最初也属于 A 类,因为它得到完整的,它的结构需要改变,它的一些行为也需要改变,因此成为 B 类的对象。所以我的方法是将抽象类视为父类,最初声明一个 C 对象但存储一个 A 对象,然后在 B 对象更改时存储它。还有另一种方法吗,比如模式???

附加信息:

我想我对此不是很清楚。假设我想将来自 A 对象的信息存储在 file1 中,并将来自 B 对象的信息存储在 file2 中。如果将其母类用作接口,那么我如何判断它是存储在相应文件中的 A 对象还是 B 对象?我应该为每个对象添加一个属性,因为它们也属于它们的文件名吗???这意味着如果我需要更改文件名,那么每个对象也需要更改。

4

3 回答 3

4

The correct way is to use virtual functions to implement polymorphic behaviour:

struct C
{
    virtual void do_crazy_stuff() { } // (see text below)
    virtual ~C() { }                  // always have a virtual d'tor for polymorphic bases
};

struct A : C
{
    virtual void do_crazy_stuff() { /* your crazy code for A */ }
};

struct B : C
{
    virtual void do_crazy_stuff() { /* your crazy code for B */ }
};

Now you can use the same interface everywhere:

void process_data(C & x)  // <-- Note: take argument by reference!!
{
    x.do_crazy_stuff();
}

This works on any object of a type derived from C:

int main()
{
    A x;
    B y;
    process_data(x);  // calls x.A::do_crazy_stuff
    process_data(y);  // calls x.B::do_crazy_stuff
}

If you like, you can even declare the base function C::do_crazy_stuff as pure virtual; this makes the base class abstract (so it cannot be instantiated).

于 2012-05-06T16:18:46.563 回答
4

First off,

C object1 = A();
C object2 = B();

slices the objects. They are no longer of type A or B, they are C.

You can use pointer for this:

C* object1 = new A();
C* object2 = new B();

Although C pointers, they point to instances of A and B respectively.

Second, your approach is wrong. It seems like you're not taking advantage of polymorphism. If you have functionality that is shared between the classes, it should be implemented in C. If it changes, you should have virtual methods.

Knowledge about the type of an object is usually at least a code smell. You can alter the behavior simply by using polymorphism. Although if it really is necessary, the correct way would be using dynamic_cast:

C* object1 = new A();
A* pA = dynamic_cast<A*>(object1);

pA will be NULL if object1 doesn't point to an object of type A.

于 2012-05-06T16:18:59.280 回答
1

This is a design issue in my opinion you have to analyze your problem better. Why do you need to know the type of your object? Why you don't implement the interface method in your A and B classes, which will do whatever you need with a binary data? Take a look on visitor design pattern to get an image of how to implement it in this way.

于 2012-05-06T16:18:42.467 回答