我在基本Polynomial类.h文件的私有部分中有以下代码:
private:
struct Term
{
float coefficient;
int power; // power of specific term
};
int degree; //total number of terms
Run Code Online (Sandbox Code Playgroud)
我有Polynomial类的以下默认构造函数:
Polynomial::Polynomial()
{
Polynomial.Term poly;
poly.power = 0;
poly.coefficient = 0;
degree = 1;
}
Run Code Online (Sandbox Code Playgroud)
我对如何访问结构中的术语以及结构外部的变量感到困惑.我试图谷歌这个,但找不到任何有用的东西.
编辑:重载输出操作员代码
ostream & operator << (ostream & outs, Polynomial & P)
{
outs << P[0].poly.coefficient << "x^" << P[0].poly.power;
for (int i=1; i<P.degree-1; i++)
{
if (P[i].poly.coefficient > 0)
outs << "+";
outs << P[i].poly.coefficient << "x^" << P[i].poly.power;
}
outs << endl;
}
Run Code Online (Sandbox Code Playgroud)
您已在构造函数中声明了该变量.一旦执行离开构造函数,该变量就会被销毁.相反,您需要将变量添加到类声明中.如果您希望能够从任何类函数外部访问成员,您还需要公开变量和结构定义.
class Polynomial
{
public:
struct Term
{
float coefficient;
int power; // power of specific term
};
Term poly;
int degree; //total number of terms
Polynomial();
};
Polynomial::Polynomial()
{
poly.power = 0;
poly.coefficient = 0;
degree = 1;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
44 次 |
最近记录: |