具有显式初始化程序的 class 的内存分配

Memory allocation for a class that has explicit initializers

当我为一些整数分配内存时,我是这样做的:

int* pointer = new int[10];

同样的事情也适用于 class 对象指针:

int dim = 5;
Complex* vect = new Complex[dim];

但是,假设我有一个 class 带有显式初始化程序,如下所示:

class Vec
{
private:
    int dim;
    Complex *vect;
public:
    Vec(int n):dim(n){
        vect=new Complex[dim];
    }
};

那么初始化指向 class 对象的指针并为其中 5 个对象分配内存的正确语法是什么?

Vec* u=new Vec(dim)[5];

语法似乎不正确。

我试过了:

    Vec* u=new Vec[2]{Vec(dim),Vec(dim)};

但这给出了错误:

Rajats-MacBook-Pro:codes rajat$ g++ vector.cpp 
vector.cpp:340:16: error: no matching constructor for initialization of
      'Vec [2]'
    Vec* u=new Vec[2]{Vec(dim),Vec(dim)};
               ^
vector.cpp:67:5: note: candidate constructor not viable: requires single
      argument 'n', but no arguments were provided
    Vec(int n):dim(n){
    ^
vector.cpp:58:7: note: candidate constructor (the implicit copy constructor) not
      viable: requires 1 argument, but 0 were provided
class Vec
      ^
1 error generated.

编辑:完整代码上传至此处:https://wandbox.org/permlink/TwsLAjg4J9tyXQEz 它适用于 WandBox。

我使用的编译器的版本信息是:

Rajats-MacBook-Pro:codes rajat$ g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.14.sdk/usr/include/c++/4.2.1
Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

谢谢。

更新:问题已解决。我需要添加编译器标志

-std=c++11

现在可以使用此处建议的所有方法。

它将是:

Vec* u = new Vec[5]{Vec(4), Vec(8), Vec(15), Vec(16), Vec(23)};

Demo

但更喜欢std::vector.

我建议改用 std::vector。例如这里:

int main() {
    std::vector<Vec> u(5, 3);
}

制作一个 5 Vec 的矢量,每个矢量 3 Complex。但是,构造函数只调用一次,然后被复制五次,所以你需要实现一个复制构造函数,否则它们将共享一个 vect:

的实例
Vec(const Vec& other){
        std::cout << "copied size " << other.dim << std::endl;
        dim = other.dim;
        vect = new int[dim];
        for (int i = 0; i < dim; i++)
            vect[i] = other.vect[i];
    }

而且为了不发生内存泄漏,你还需要一个析构函数:

~Vec() {
    delete[] vect;
    std::cout << "deleted " << dim << std::endl;
}

两者不是同一种情况,首先你在编译时知道向量的大小。最好尝试使用 std::vector,这样你就不用担心内存管理问题了。

class Vec
{
private:
    int dim;
    std::vector<Complex> vect;
public:
    Vec(int n):dim(n){
        vect.resize(dim);
    }
};