我在C ++代码中有一种奇怪的行为。我有一个抽象的基类符号:
template <class C, class E>
class Symbolic
{
protected:
vector<pair<C, E> > monomials;
public:
virtual ~Symbolic() {}
virtual ostream &print(ostream &o) const = 0;
virtual void add_monomial(C, E) = 0;
};
在我的派生类Theta2中,我想实现add_monomial方法,在其中我尝试将一对推回到向量单项式。
class Theta2 : public Symbolic<Complex, double>
{
protected:
size_t n;
public:
Theta2(size_t n);
Theta2(const Theta2 &);
~Theta2();
ostream& print(ostream &) const;
void add_monomial(Complex c, double e);
};
ostream & operator<<(ostream &, const Theta2 &);
这就是该方法的实际实现:
void Theta2::add_monomial(Complex c, double e)
{
this->monomials.push_back(make_pair(c, e));
}
Complex是我实现为GNU MPC库的包装器的类型。
这就是我称之为方法的方式:
int main (int argc, char **argv)
{
Theta2 t2(7);
cout << "Adding monomials" << endl;
t2.add_monomial(Complex(1), 0);
t2.add_monomial(Complex(2), 1);
t2.add_monomial(Complex(3), 2);
t2.add_monomial(Complex(4), 3);
t2.add_monomial(Complex(5), 4);
t2.add_monomial(Complex(6), 5);
cout << "Theta2:" << t2 << endl;
return EXIT_SUCCESS;
}
我的实际问题是,我的程序打印出“添加单项目”,但随后终止,没有任何错误消息。我调试了程序,它调用方法add_monomials但在push_back之后终止。
编辑:这是我的复杂定义:
enum ComplexPart {REAL, IMAG};
class Complex {
private:
mpc_t c;
public:
static const mpfr_prec_t PREC;
Complex();
Complex(long double re);
Complex(long double re, long double im);
Complex(const Complex &);
virtual ~Complex();
void add(const Complex &other);
Complex add(const Complex &other) const;
string get_mpfr_string(mpfr_t number, size_t digits) const;
string get_cplx_part(ComplexPart which, size_t digits) const;
Complex &operator=(const Complex &);
virtual ostream& print(ostream &o) const;
};
ostream &operator<<(ostream &o, const Complex &c);
这是实施:
const mpfr_prec_t Complex::PREC = 1024;
Complex::Complex()
{
mpc_init2(this->c, Complex::PREC);
}
Complex::~Complex()
{
mpc_clear(this->c);
}
Complex::Complex(const Complex &other)
{
mpc_set(this->c, other.c, MPC_RNDNN);
}
Complex::Complex(long double re)
{
mpc_init2(this->c, Complex::PREC);
mpc_set_ld(this->c, re, MPC_RNDNN);
}
Complex::Complex(long double re, long double im)
{
mpc_init2(this->c, Complex::PREC);
mpc_set_ld_ld(this->c, re, im, MPC_RNDNN);
}
Complex &Complex::operator=(const Complex &c)
{
mpc_set(this->c, c.c, MPC_RNDNN);
return *this;
}
感谢所有评论者。这是解决方案。问题是我的拷贝构造函数中缺少mpc_t c的初始化:
Complex::Complex(const Complex &other)
{
mpc_init2(this->c, Complex::PREC);
mpc_set(this->c, other.c, MPC_RNDNN);
}