gpt4 book ai didi

c++ - 具有显式初始化程序的类的内存分配

转载 作者:行者123 更新时间:2023-11-28 04:07:42 26 4
gpt4 key购买 nike

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

int* pointer = new int[10];

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

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

但是,比如说,我有一个像这样带有显式初始化器的类:

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

那么初始化指向类对象的指针并为其中的 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

关于c++ - 具有显式初始化程序的类的内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58427445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com