同一程序中使用一种数据结构时有多种不同的元素类型,最好的处理方式是?

不同的数据单元(Node)使用同一种数据结构的实现,在程序中怎么处理最好?

阅读 4.8k
3 个回答
enum TypeId {String, Int, Bool, /* ... */ }

struct Value {
  TypeId type;
  union {
    char* stringValue;
    int intValue;
    bool boolValue;
    /* ... */
  }
}

这么搞可以吗?弱弱的说。

更新:

这种方法采用了“Command Pattern“,虽然和题主的要求有所出入,但是实现了接口的一致。其实也不算一个坏方法吧。

附链接:http://en.wikipedia.org/wiki/Command_pattern

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class ivar {
public:
    virtual void show() = 0;
    virtual ~ivar(){}
};

class IntVar: public ivar {
public:
    IntVar(int i_value):
        value(i_value){}
    virtual void show() 
    {
        cout << value << endl;
    }
private:
    IntVar(){}
    int value;
};

class StringVar: public ivar {
public:
    StringVar(string i_value):
        value(i_value){}
    virtual void show()
    {
        cout << value << endl;
    }
private:
    string value;
};

int main()
{
    vector<ivar*> var_list;
    var_list.push_back(new IntVar(3));
    var_list.push_back(new StringVar("abc"));
    var_list.push_back(new IntVar(123));

    for (int i = 0; i < (int)var_list.size(); i++) {
        var_list[i]->show();
    }

    for (int i = 0; i < (int)var_list.size(); i++) {
        delete var_list[i];
    }

    return 0;
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题