c++ - 如何在其他类的参数模板中使用某个类?

标签 c++ templates

我有两个类 PolynomFraction

我需要为 Polynom 做一个模板,以便在 Polynom 中使用 Fraction 系数,例如:3/4 x ^0 + 5\6 x^1

我了解如何使用像 doubleint 这样的简单类型,但是如何让它为我不知道也找不到的类工作关于这个主题的 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.
}

那么,PolynomTFraction 的类构造函数,以及如何重载运算符呢?

最佳答案

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/

相关文章:

c++ - 为什么 `wstring_convert` 抛出 range_error?

c++ - 检查类型是否具有在 C++ 中定义的 [][]

c++ - 派生模板类访问基类成员数据

c++ - 如何在#ifdef 中添加 'or' 条件

c++ - 如何初始化 std::array<std::atomic<bool>> — 没有复制或移动 ctors

c++ - 编译器是否优化了未使用的参数?

c++ - 如何约束模板参数以符合 std::map 中的键?

c++ - 使用 GPGME 加密灵活的数据量

所有指针的 C++ 模板和所有数组的模板

c++ - 容器模板参数 std::map 或 std::vector