我有两个类 Polynom
和 Fraction
。
我需要为 Polynom
做一个模板,以便在 Polynom
中使用 Fraction
系数,例如:3/4 x ^0 + 5\6 x^1
等
我了解如何使用像 double
或 int
这样的简单类型,但是如何让它为我不知道也找不到的类工作关于这个主题的 Material 。
class Fraction {
private:
int numerator, denominator;
public:
Fraction();
Fraction(int, int);
Fraction(int);
}
template<class T>
class PolynomT {
private:
int degree;
T *coef;
public:
PolynomT();
explicit PolynomT(int, const T * = nullptr);
~PolynomT();
};
template<class T>
PolynomT<T>::PolynomT(int n, const T *data): degree(n) {
coefA = new T[degree+1];
if (data == nullptr) {
for (int i = 0; i < degree+1; ++i)
coefA[i] = 0.0;
}
else {
for (int i = 0; i < degree + 1; ++i)
coefA[i] = data[i];
}
}
/*Problem here*/
int main() {
PolynomT<Fraction> a(); // what need to pass on here in arguments?
// how should the constructor look like?
/*Example*/
PolynomT<Fraction> b();
PolynomT<Fraction> c = a + b; // or something like this.
}
那么,PolynomT
中Fraction
的类构造函数,以及如何重载运算符呢?
最佳答案
PolynomT
构造函数中的 coefA[i] = 0.0
赋值出现问题是因为 Fraction
没有采用 a 的构造函数double,它也没有接受 double 的赋值运算符。有几种可能的解决方案。
将 coefA
的原始内存管理更改为 std::vector
。
std::vector<T> coefA;
// Then resize appropriately in the constructor
这会自动用默认构造的对象填充所有元素,因此如果 data == nullptr
,您不需要做任何事情。
另一种可能性是将分配更改为
coefA[i] = T();
这将分配一个默认构造的对象类型(0.0 为 double )。
What are the basic rules and idioms for operator overloading有关于重载运算符的详细信息。
关于c++ - 如何在其他类的参数模板中使用某个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142123/