c++ - 同一程序中使用一种数据结构时有多种不同的元素类型,最好的处理方式是?
迷茫
迷茫 2017-04-17 11:12:54
[C++讨论组]

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

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(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;
}
PHPz

Boost Variant

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号