c++ - 在类中定义变量

标签 c++ class

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

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

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

invalid use of non-static data member  int n;

当我将 n 设置为 static 时,会出现以下错误

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

这是关于单独编译头文件的。我究竟做错了什么?

最佳答案

你的类包含 VLA(可变长度数组),它不是 C++ 支持。

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

class Polynomial
{
  static const int n = 10;
  double a[n];
  ...

class Polynomial
{
  std::vector<double> a;

关于c++ - 在类中定义变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33294365/

相关文章:

c++ - seekg() 没有按预期工作

c++ - 使用 C++ 递归打印链表

C++ : Accessing private member of base or global variable from a derived class

c++ - Makefile 头目录错误

java - 返回所有值的问题

Java Jackson 序列化器,包括 FQCN

c++ - 如何将客户端类与模板类分离?

c++ - 当转发声明类时,我也应该在那里使用属性定义吗?

python - __init__ 总是需要的吗?

python - Python getslice项目运算符覆盖功能不起作用