c++ - 瞬时变量的值未分配与传递给构造函数的值相同

标签 c++ oop constructor

我正在做一个与插入排序相关的问题(这不是我的问题)但我遇到了以下问题。

(问题从这里开始) 我创建了一个构造函数,其中将 5 传递给 size 变量。 但是在构造函数中分配 i cout<<this->size; 后它显示 1 但我期待 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;
}

我很期待 size 5 This->size 5 但它正在给予 size 5 This->size 1 你可以查看我的main()功能:

main() { int arr[]= {1,5,4,8,3}; InsertionSort a(&arr[0], 5); }

当我用这些值创建对象时:

InsertionSort a(&arr[1], 5);

分配给 this->size 的值在 arr[1] 处变为 5 i-e 值

请指正我做错的地方。

最佳答案

定义

int array[];

类的内部应该在类定义的末尾,除非你设置了一个固定的大小 如果你想要它的动态大小,通过声明它来使用动态分配

int *array;

在构造函数中,使用

this->array = new int[size];

至于线

this->array[size];

没有任何意义..

关于c++ - 瞬时变量的值未分配与传递给构造函数的值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941977/

相关文章:

C++ 转换派生为 void* 并恢复基数

c++ - 函数指针是否不支持 C++ 中的实例类型

c++ - Windows XP 与 Vista/7 上的 MS Crypto API 行为

java - 有一个空方法可以吗?

oop - 这里需要抽象类吗?

c++ - C++中抛出异常的两种方法(不使用堆)

c++ - 这个 backward_warning.h #warning 来自哪里?

java - 控制反转和依赖注入(inject)之间的区别

c++ - 即使存在转换,也无法将子类模板转换为基类的另一个模板

c++ - SDL_Surface* 作为 C++ 中的构造函数参数