在类中定义变量
Defining variables in a 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
这只是头文件中多项式类的一部分。当我尝试编译时,它给了我以下错误
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;
}
}
关于动态内存分配的更详细的解释请参见此链接。
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值