gpt4 book ai didi

C++ 类型转换与隐式构造函数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:39:44 25 4
gpt4 key购买 nike

我正在实现一个表示分数的 C++ 类。这是我的代码。

class Fraction
{
public:
Fraction(char i);
Fraction(int i);
Fraction(short i);
Fraction(long int l);
#ifdef __LP64__
Fraction(long long l);
#endif
Fraction(float f);
Fraction(double d);
Fraction(double x, double y);

Fraction operator +() const;
Fraction operator -() const;

Fraction& operator +=(const Fraction& other);
Fraction& operator -=(const Fraction& other);
Fraction& operator *=(const Fraction& other);
Fraction& operator /=(const Fraction& other);

bool operator ==(const Fraction& other);
bool operator !=(const Fraction& other);
bool operator >(const Fraction& other);
bool operator <(const Fraction& other);
bool operator >=(const Fraction& other);
bool operator <=(const Fraction& other);

operator double();
operator float();

static void commonize(Fraction& a, Fraction& b);
void shorten();

double getNumerator();
double getDenominator();

friend Fraction operator +(Fraction const& a, Fraction const& b);
friend Fraction operator -(Fraction const& a, Fraction const& b);
friend Fraction operator *(Fraction const& a, Fraction const& b);
friend Fraction operator /(Fraction const& a, Fraction const& b);
friend ostream& operator <<( ostream& o, const Fraction f);

protected:
double numerator, denominator;

};

我现在有两个小问题。现在正在尝试调用

Fraction a(1, 2);
cout << (3 + a) << endl;

只会导致这个错误:

fractiontest.cpp:26: error: ambiguous overload for ‘operator+’ in ‘3 + a’
fractiontest.cpp:26: note: candidates are: operator+(int, double) <built-in>
fractiontest.cpp:26: note: operator+(int, float) <built-in>

我真正想要的是:

explicit operator double();
explicit operator float();

但显然,这是行不通的。如果我使用强制转换符号,我希望这两个强制转换运算符被称为。例如 Fraction f(1, 2);双 d = (双)(f);

最佳答案

根据定义,转换运算符是隐式。你不能让他们明确。

正常的解决方案是命名成员函数来进行转换。我认为您还可以创建一个看起来像 static_cast 的专用模板方法,然后调用显式类方法。

关于C++ 类型转换与隐式构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6207936/

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