c++ - Value of instantaneous variable is not assigned same as passed to Constructor
问题描述
I am doing a problem related to Insertion Sort (this is not my problem) but i am having the following problem.
(Problem starts here)
I create a constructor where is am passing 5 to size variable.
But when in Constructor after assignment i cout<<this->size;
it displays 1 but i am expecting 5
class InsertionSort{
public:
int array[];
int size;
InsertionSort(int *array, int size);
void sort();
void displayArray();
};
InsertionSort::InsertionSort(int array[], int size){
this->array[size];
this->size= size;
for(int i=0; i<size; i++){
this->array[i]= array[i];
}
//here is the cout
cout<<"size "<<size<<endl;
cout<<"This->size "<<this->size<<endl;
}
I am expecting
size 5
This->size 5
but it is giving
size 5
This->size 1
You can check my main()
function:
main() {
int arr[]= {1,5,4,8,3};
InsertionSort a(&arr[0], 5);
}
When i create object with these values:
InsertionSort a(&arr[1], 5);
value of assigned to this->size
becomes 5 i-e value at arr[1]
Please correct me where i am doing something wrong.
解决方案
defining
int array[];
inside of a class should be at the end of the class definition unless you're setting a fixed size if you want it to a dynamic size, use dynamic allocation by declaring it like
int *array;
and in the constructor, use
this->array = new int[size];
as for the line
this->array[size];
it has no meaning..
推荐阅读
- r - 如何在R中按组在数据帧列中迭代地除以最后一个观察值,然后存储结果
- list - 从两个列表中创建元组
- javascript - 在 for 循环中向对象添加键值对
- vhdl - 在 VHDL 设计中是否推荐使用时钟?
- javascript - 是否可以从 JavaScript 中的 if 语句的主体将新字符串附加到 if 语句之外的变量?
- google-cloud-platform - 从谷歌云扳手数据库部署数据
- r - 如何通过使用 R 选择正确的输入从网站下载数据(查询不会更改 URL)
- python - 键入并选择条目时过滤列表
- android - 用 onclick 监听器替换列表视图不起作用
- php - 如何按名称获取数据 Codeigniter