我正在尝试使用具有相同类对象的函数运算创建一个 fractionType 类,我还使用了一个模板,以便可以使用 int、float 或 double 构造 fractionType 对象。我一直在寻找一个又一个问题的解决方案,所以我需要帮助解决此代码中的上述错误:
main.cpp:
#include <iostream>
#include "fractionType.h"
using namespace std;
int main()
{
fractionType<int> x(4, 2);
fractionType<double> y(5.2, 6.8);
fractionType<float> z(1.0, 1.0);
z = x + y;
return 0;
}
分数类型.h:
#ifndef FRACTIONTYPE_H
#define FRACTIONTYPE_H
using namespace std;
template <class T>
class fractionType;
template <class T>
class fractionType
{
public:
explicit fractionType();
explicit fractionType<T>(T num, T den);
T numerator;
T denominator;
};
template <class T>
fractionType<T>::fractionType()
{
}
template <class T>
fractionType<T>::fractionType(T num, T den)
{
numerator = num;
denominator = den;
}
template <typename U, typename V>
fractionType<int> operator + (const fractionType<U>& fraction1, const fractionType<V>& fraction2)
{
fractionType<int> tempFraction(1,1);
tempFraction.numerator = (fraction1.numerator * fraction2.denominator + fraction1.denominator * fraction2.numerator);
tempFraction.denominator = (fraction1.denominator * fraction2.denominator);
return tempFraction;
}
#endif
错误:
main.cpp: In function ‘int main()’:
main.cpp:10:13: error: no match for ‘operator=’ (operand types are ‘fractionType’ and ‘fractionType’)
10 | z = x + y;
| ^
In file included from main.cpp:2:
fractionType.h:10:7: note: candidate: ‘fractionType& fractionType::operator=(const fractionType&)’
10 | class fractionType
| ^~~~~~~~~~~~
fractionType.h:10:7: note: no known conversion for argument 1 from ‘fractionType’ to ‘const fractionType&’
fractionType.h:10:7: note: candidate: ‘fractionType& fractionType::operator=(fractionType&&)’
fractionType.h:10:7: note: no known conversion for argument 1 from ‘fractionType’ to ‘fractionType&&’
有什么建议吗?
在语句
z = x + y;
中,表达式x + y
返回一个fractionType<int>
,但是z
是一个fractionType<float>
。您尚未定义允许该分配的转换,因此出现错误。
您可以:
*this
对象构造fractionType
,例如:template <class T>
class fractionType
{
public:
...
template <typename U>
fractionType(const fractionType<U> &src) {
numerator = static_cast<T>(src.numerator);
denominator = static_cast<T>(src.denominator);
}
};
fractionType
对象赋值给*this
,例如:template <class T>
class fractionType
{
public:
...
template <typename U>
fractionType<T>& operator=(const fractionType<U> &rhs) {
numerator = static_cast<T>(rhs.numerator);
denominator = static_cast<T>(rhs.denominator);
return *this;
}
};
*this
转换为其他类型的fractionType
对象,例如:template <class T>
class fractionType
{
public:
...
template <typename U>
operator fractionType<U>() const {
return fractionType<U>(static_cast<U>(numerator), static_cast<U>(denominator));
}
};