【问题标题】:Struggling with the declaration of class attributes inside the C++ header file?为 C++ 头文件中的类属性声明而苦苦挣扎?
【发布时间】:2020-04-26 11:21:46
【问题描述】:

作为一名 C++ 初学者,我经常发现自己在头文件中声明类属性时遇到了困难,这些属性需要更多信息而不仅仅是名称,例如 arraysobjects其他类的构造函数。

这是一个例子

SomeClass.h :

#include "OtherClass.h"

class SomeClass {

  int num; // works fine
  float arr[]; // produces an error because size is not declared

  OtherClass obj; // produces an error because the constructor parameters are not passed in

public:
  void setup();
  void update();

};

SomeClass.cpp:

#include "SomeClass.h"

void SomeClass::setup() {
  num = 10; // easy peasy, works!
  arr = float some_arr[5 * num]; // error

  // Fill in the array
  for (int i = 0; i < 5 * num; i += num) {
    ass[i] = 12;
  }

  // Fill in the class attributes
  obj = {120, 40}; // error

}

void SomeClass::update() {
  // Update stuff
}

如果是数组arr,如果在头文件中声明时我不知道它的大小,我该如何声明一个数组?

如何在头文件中声明带有构造函数的类对象,而此时不传入未知参数?

谢谢。

【问题讨论】:

    标签: c++ class oop


    【解决方案1】:

    如果是数组arr,如果我不知道如何声明数组 在头文件中声明时的大小?

    你不能! C++ does not support variable length arrays,虽然 一些 编译器(例如 GCC)添加了对它们作为扩展的支持。

    相反,您应该考虑使用std::vector 容器类型,来自Standard Template Library

    在您的标题/声明中:

    class SomeClass {
        int num; // works fine
    //  float arr[]; // produces an error because size is not declared
        std::vector<float> arr;
        //...
    };
    

    并且,对于您的 setup() 函数:

    void SomeClass::setup() {
        num = 10; // easy peasy, works!
    //  arr = float some_arr[5 * num]; // error
        arr.resize(5 * num); // Sets the size of the container
        // Fill in the array...
        for (int i = 0; i < 5 * num; i += num) {
            arr[i] = 12; // You can access (valid) elements just like a normal array!
        }
        //...
    }
    

    【讨论】:

    • 感谢您的选择!也很好用。关于我的类对象问题的任何想法?
    【解决方案2】:

    如果您事先不知道数组大小,您可以使用 C++ 中的动态分配功能。

    首先声明你的数组变量如下

    float *arr;
    

    然后您可以按如下方式分配所需的大小

    arr=new float[10]; 
    

    释放内存

    delete[] arr;
    

    如果要动态分配对象,则声明类为

    ClassName *obj;
    

    然后分配使用

     obj=new ClassName(your_parameters);
    

    然后你可以使用删除它

    delete obj;
    

    提示: 在释放内存后将指针变量设为 NULL 始终是一个好习惯。 做 arr=NULL;和 obj=NULL;取消分配后

    【讨论】:

    • 如果您要“鼓励”使用原始指针,那么您还应该指出需要delete[] arr; 语句(在析构函数中)。
    • @BRUCE - 谢谢,就像一个魅力!您是否有机会知道这是否也适用于类对象(带有构造函数)?
    • @St4rb0y - 如果你的意思是像我在数组中那样动态分配内存,我已经编辑了答案,请检查一下
    猜你喜欢
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    相关资源
    最近更新 更多