如何构造初始化器和双端队列

时间:2014-10-27 20:15:44

标签: c++

所以我有..

struct Polynomial{
    deque<long> coefs;
    long degree;

    Polynomial(initializer_list<long> co_list);
    Polynomial(deque<long> & co_list);
    Polynomial();
    string poly_to_string();
    Polynomial add(Polynomial rhs);
    Polynomial mult(Polynomial rhs);
    Polynomial mult(long factor);
}

对于theese方法,我必须:

多项式(initializer_list cfs)。使用初始化系数列表初始化实例。 -order是最高功率,最低功率 -coefs和学位更新。

多项式(deque cfs)。使用系数向量初始化实例。 -order是最高功率,最低功率 -coefs和学位更新。

然后我做方法来添加/倍数/因子多项式,我可以做,只是不确定是什么

Polynomial(initializer_list<long> co_list);
Polynomial(deque<long> & co_list);

假设要做/如何启动它们。

另外,我将如何启动函数返回     Polynomial.degree 要返回一个长值?

1 个答案:

答案 0 :(得分:0)

这两个函数是该类型的构造函数。它们告诉编译器如何设置Polynomial对象,以便为成员调用它。他们最容易被理解为:

struct Polynomial{
    deque<long> coefs;
    long degree;

    Polynomial(initializer_list<long> co_list);
    Polynomial(deque<long> & co_list);
};
Polynomial::Polynomial(initializer_list<long> co_list) 
{
    //at this point, the members are created, but have no values
    //so we assign values to the members
    coefs.assign(co_list.begin(), co_list.end());
    degree = co_list.size();
}  
int main() 
{
    Polynomial mypoly = {3, 4, 5}; 
    //creates a Polynomial variable from an initializer list
    //the compiler runs the constructor function automatically
    //so now it's members are all properly set, and we can run other functions
    mypoly.do_thing();
}

但是,如上所示,Polynomial构造函数构造了两个成员,然后执行为其赋值的函数。我们可以通过直接使用预期值构建它们来使这更好:

Polynomial::Polynomial(initializer_list<long> co_list) 
    :
    coefs(co_list.begin(), co_list.end()), //constructed directly
    degree(co_list.size())
{
    //they already have the needed values, don't need to do anything more
    //to finalize the construction
}