首页 > 解决方案 > 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.

标签: c++oopconstructor

解决方案


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..


推荐阅读