您的位置:首页 > 其它

杂货边角(20):匿名非受限联合体实现类的“变长成员”variant member

2018-02-25 10:09 330 查看
#include <iostream>
#include <cstring>

using namespace std;

/*
联合体的使用,最主要的效果便是内存空间的节省,当然额外的附加作用便是灵活性,但是这种灵活性是以牺牲
可读性为代价的
*/
union T {
string s;//因为string 是非POD类型,string有non-trivial的构造函数,故而系统会删除T的默认构造函数
//error: union member 'T::s' with non-trivial 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string() [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]'|
int n;
public:
T() { new (&s) string; } //placement new机制,直接在地址上强制类型初始化
~T() { s.~string(); }
};

struct Student{
Student(bool g, int a) : gender(g), age(a) {}
bool gender;
int age;
};

class Singer {
public:
enum Type {STUDENT, NATIVE, FOREIGNER};

Singer(bool g, int a): s(g,a) { t = STUDENT; }
Singer(int i) : id(i) { t = NATIVE; }
Singer(const char* n, int s) {
int size = (s>9) ? 9 : s;
memcpy(name, n, size);
name[s] = '\0';
t = FOREIGNER;
}

~Singer() {}
private:
Type t;
union { //C++11引入的匿名的非受限结构体,从而配合类,可实现“变长成员”定义的效果variant member
Student s;
int id;
char name[10];
};
};

int main()
{
T t; //因为T的默认构造函数被删除了,所以如果不显示定义,则会出现error: use of deleted function 'T::T()'

Singer a(true, 24);
Singer b(85767);
Singer c("Jack chou", 41);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  union 变长成员
相关文章推荐