在类中定义变量

Defining variables in a class

本文关键字:变量 定义      更新时间:2023-10-16

我正在编写一个多项式程序,下面是我为它编写的代码。

class Polynomial{
private:
int n;  //n = degree of polynomial
double a[n];            //a = array of coefficients where a[i] is the coefficient of x^i
double roots[n];
double maxima[n-1],minima[n-1],inflection[n-1]; //arrays of coordinates of maxima, minima and points of inflection

这只是头文件中多项式类的一部分。当我尝试编译时,它给了我以下错误

invalid use of non-static data member  int n;

,当我将n设置为静态时,它会给出以下错误

 array bound is not an integer constant before ‘]’ token

这是单独编译头文件。我做错了什么?

你的类包含VLA(可变长度数组),它不是

您需要通过使n恒定来确定大小或者使用另一种动态容器std::vector是一个容器,类似于一个数组,但是动态的,即可以在运行时展开。

class Polynomial
{
  static const int n = 10;
  double a[n];
  ...
class Polynomial
{
  std::vector<double> a;

c风格数组的大小必须在编译时知道。

如果n在编译时是已知的,可以将其作为模板形参而不是成员变量。

如果没有,那么你必须使用不同的容器,如vector<double> a, roots, maxima, minima, inflection;

您可以简单地在使用new的构造函数中分配所有这些。使用vector

class Polynomial
{
    vector<double> a;
    Polynomial()
    {
        a.assign(n,0);
        ...
    }
..
};

不讲复杂,

简单的答案是,对于静态内存分配工作(这是你试图用double a[n];做的),你需要在编译时知道数组的大小。

但是,如果在程序运行之前不知道数组的大小,而是期望在程序运行时的某个地方知道它的大小,则需要使用动态内存分配

要做到这一点,你必须

  • 声明指针而不是静态数组

  • 使用new指令为它们分配内存

,然后

  • 当你不需要它们时,例如当类的作用域结束时,你将不得不使用delete指令和[]括号来释放你分配的内存,以指示编译器为多个连续的变量释放内存。

执行如下命令:

class Polynomial{
private:
int n; //n = degree of polynomial
double *a; //a = array of coefficients where a[i] is the coefficient of x^i
double *roots;
double *maxima,*minima,*inflection; //arrays of coordinates of maxima, minima and points of inflection
public:
 Polynomial( int degree_of_polynomial ){
     n = degree_of_polynomial;
     a = new double[n];
     roots = new double[n]; 
     maxima = new double[n-1];
     minima = new double[n-1];
     inflection = new double[n-1];
     ~Polynomial(){
        delete []a;
        delete []roots;
        delete []maxima;
        delete []minima;
        delete []inflection;
    }
 }

关于动态内存分配的更详细的解释请参见此链接。