你真的在初始化多项式吗?这样做new int[degree_ + 1];
不会构造一个初始化的数组,它的值是垃圾。
编辑:除非有另一个很好的理由需要 a int*
,否则最好使用 astd::vector
作为多项式系数容器。它将简化对象的构造、销毁和分配。
这很好用(这意味着问题出在您没有向我们展示的代码部分:类定义和赋值运算符)
class Polynomial
{
public:
Polynomial();
Polynomial( const Polynomial& p );
template <int N> Polynomial(int (&Poly)[N] );
Polynomial& operator=( const Polynomial& Rhs);
void Print();
~Polynomial();
private:
int* poly_;
int degree_;
};
class FiniteFieldElement
{
public:
FiniteFieldElement( Polynomial P );
void Print();
private:
Polynomial p_;
};
和实现:
Polynomial::Polynomial()
{
degree_ = 0;
poly_ = new int[degree_ + 1];
poly_[0] = 1;
}
// excessive, you don't really need this
template <int N> Polynomial::Polynomial(int (&Poly)[N] )
{
degree_ = N - 1;
poly_ = new int[degree_ + 1];
for (int i = 0; i <= degree_; i++)
{
poly_[i] = Poly[i];
}
}
Polynomial& Polynomial::operator=( const Polynomial& Rhs)
{
if ( this != &Rhs )
{
degree_= Rhs.degree_;
delete[] poly_;
poly_ = new int[degree_ + 1];
for (int i = 0; i <= degree_; i++)
{
poly_[i] = Rhs.poly_[i];
}
}
return *this;
}
void Polynomial::Print()
{
std::cout<< "Degree = " << degree_ << "\n Polynomial = ";
for (int i = 0; i <= degree_; i++)
{
std::cout<< poly_[i] << " ";
}
std::cout<<"\n";
}
Polynomial::~Polynomial()
{
delete[] poly_;
}
Polynomial::Polynomial(const Polynomial& p)
{
degree_ = p.degree_;
poly_ = new int[degree_ + 1];
for (int i = 0; i <= degree_; i++)
{
poly_[i] = p.poly_[i];
}
}
和
FiniteFieldElement::FiniteFieldElement( Polynomial P )
{
p_ = P;
}
void FiniteFieldElement::Print()
{
p_.Print();
}
主要只是:
int main(int argc, _TCHAR* argv[])
{
int myPoly[] = { 1, 2, 3 };
Polynomial foo(myPoly);
FiniteFieldElement bar( foo );
std::cout<< "Foo:\n";
foo.Print();
std::cout<< "Bar:\n";
bar.Print();
return 0;
}
如果它在您的机器上运行,请查看它在代码和行为方面与您的实现有何不同。