gpt4 book ai didi

c++ - 为 C++ Variant 类在 string、int、double 之间灵活转换

转载 作者:可可西里 更新时间:2023-11-01 14:57:11 26 4
gpt4 key购买 nike

我正在实现一个变体类(不使用 boost),我想知道您将如何处理存储字符串、整数或 double 中的任何一个并通过 ToString 将其相应地自动转换为所需类型的情况()、ToInt() 或 ToDouble()。

例如,

Variant a = 7;
cout << "The answer is" + a.ToString() << endl; // should print "The answer is 7"
a = "7.4";
double &b = a.ToDouble();
b += 1;
cout << a.ToString() << endl; // should print 8.4

ToXXX 函数应该返回您要转换成的类型的引用。现在,我有代码可以返回与最初分配给它相同的类型( Variant a = Int(7); a.ToInt() 工作)并在分配类型时引发异常与您要转换为的目标不同。

抱歉,不能使用 boost。

最佳答案

    #include <string>
#include <iostream>
class Variant{
public:
Variant(){
data.type = UNKOWN;
data.intVal = 0;
}
Variant(int v){
data.type = INT;
data.intVal = v;
}
Variant(double v){
data.type = DOUBLE;
data.realVal = v;
}
Variant(std::string v){
data.type = STRING;
data.strVal = new std::string(v);
}
//the missing copy constructor
Variant(Variant const& other)
{
*this = other;// redirect to the copy assignment
}

~Variant(){
if(STRING == data.type){
delete data.strVal;
}
}

Variant& operator = (const Variant& other){
if(this != &other)
{
if(STRING == data.type){
delete data.strVal;
}

switch(other.data.type){
case STRING:{
data.strVal = new std::string(*(other.data.strVal));
data.type = STRING;
break;
}
default:{
memcpy(this, &other, sizeof(Variant));
break;
}
}
}
return *this;
}
Variant& operator = (int newVal){
if(STRING == data.type){
delete data.strVal;
}
data.type = INT;
data.intVal= newVal;
return *this;
}

Variant& operator = (double newVal){
if(STRING == data.type){
delete data.strVal;
}
data.type = DOUBLE;
data.realVal= newVal;
return *this;
}

Variant& operator = (std::string& newVal){
if(STRING == data.type){
delete data.strVal;
}
data.type = STRING;
data.strVal= new std::string(newVal);
return *this;
}
operator int&() {
if(INT == data.type)
{
return data.intVal;
}
//do type conversion if you like
throw std::runtime_error("bad cast");
}

operator double&() {
if(DOUBLE == data.type){
return data.realVal;
}
//do type conversion if you like
throw std::runtime_error("bad cast");
}
operator std::string&() {
if(STRING == data.type){
return *data.strVal;
}
throw std::runtime_error("bad cast");
}
private:
enum Type{
UNKOWN=0,
INT,
DOUBLE,
STRING
};
struct{
Type type;
union
{
int intVal;
double realVal;
std::string* strVal;
};
} data;
};


int main(){
Variant v("this is string");//string
v=1;//int
v=1.0;//double
v=std::string("another string");//
Variant v2; //unkown type
v2=v;//string
std::cout << (std::string&)v2 << std::endl;
return 0;
}

关于c++ - 为 C++ Variant 类在 string、int、double 之间灵活转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8173389/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com