Разбира се си прав, zaphod нещо се глези. Всънщост ние джигитите и сега можем да пъхаме класове в union-и, ето пример как се прави:
#include <cassert>
#include <string>
#include <iostream>
class Var
{
enum VT
{
VAR_NONE,
VAR_INT,
VAR_REAL,
VAR_STRING,
};
union
{
int _int;
double _double;
char _string[sizeof(std::string)];
};
VT vt;
public:
Var( int i ) : vt(VAR_INT), _int(i) {}
Var( const std::string s )
: vt(VAR_STRING)
{
new ( static_cast<void*>(_string) ) std::string(s);
}
~Var()
{
using namespace std;
switch(vt)
{
case VAR_STRING:
reinterpret_cast<string&>(_string).~string();
//break;
}
vt = VAR_NONE;
}
const std::string &AsString(void) const
{
// should throw an exception if tipe does not match.
assert(vt==VAR_STRING);
return reinterpret_cast<const std::string&>(_string);
}
private:
Var( const Var & ); // should be defined if needed
Var& operator=( const Var & ); // should be defined if needed
};
void main(void)
{
Var vi(5);
Var vs("asdf");
std::cout << vs.AsString() << std::endl;
}
System Doctor Error:
Your girlfriend is pregnant.
(A)bort, (M)arry, (I)gnore?_Редактирано от Colombino на 22.05.05 23:43.