如何用c++编写默认的隐式转换器?

问题描述 投票:0回答:1

这里我在

c++
有一个类,它处理远远超出
long long
的大量数字。它将数据存储为
std::string
。现在我这里有很多很多转换器:

class BigInt {
private:
    std::string x;
public:
    operator std::string()        { return x;              }
    operator int()                { return std::stoi(x);   }
    operator long long()          { return std::stoll(x);  }
    operator unsigned long long() { return std::stoull(x); }
    operator double()             { return std::stod(x);   }
    operator long double()        { return std::stold(x);  }
    ...
    BigInt(std::string a) : x(a) {}
    BigInt(long long a) : x(to_string(a)) {}
    ...
}
int main() {
    BigInt x = 10485761048576;
    std::cout << x << std::endl; // Error!
}

但是发生的事情是我收到错误:

多个运算符与这些操作数匹配。

这基本上意味着函数

std::cout
不知道选择哪个转换器。那么是否有一种“默认”转换器可以在访问函数时选择其中一个转换器作为默认转换器?

如果没有那种东西,那么我想我每次想将参数传递给某种重载函数时都必须调用类似

std::cout << (std::string)x << std::endl;
的东西。

c++ class implicit-conversion
1个回答
0
投票

您可以使用

std::ostream
operator<<
BigInt
提供过载:

std::ostream& operator<<(std::ostream& os, const BigInt& obj)
{
  os << (std::string)x;
  return os;
}

现在您可以使用:

int main() {
    BigInt x = 10485761048576;
    std::cout << x << std::endl;
}

输出:

10485761048576
© www.soinside.com 2019 - 2024. All rights reserved.