c++ 如何使用std::cout < < 一个有许多(模糊的)用户定义转换函数的类型?

hk8txs48  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(112)

这里我有一个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;的东西。

egdjgwm8

egdjgwm81#

您可以为BigInt提供std::ostreamoperator<<的重载:

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

为了能够对const对象使用转换运算符(就像上面的operator<<一样,这是一个很好的做法),你还需要将它们标记为const**,例如:

//  -----------------------vvvvv--------------
    operator std::string() const { return x; }

现在您可以用途:

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

输出量:

10485761048576

Live demo - Godbolt

相关问题