将 new 运算符与对象的非默认构造函数一起使用

Using the new operator with an object's non-default constructor

本文关键字:构造函数 默认 一起 new 运算符 对象      更新时间:2023-10-16

想要什么:

classname* p = new classname(parameter1, parameter2, ...); 

创建一个指针,指向使用签名为classname(parameter1, parameter2, ...)的非默认构造函数初始化的对象?

谢谢!

是的,这是正确的。



我自己说得再好不过了——不过,完成后记得删除它,除非你想让堆不开心!

是的,会的。这个程序说明了这个概念。

#include <string>
#include <iostream>
class Foo
{
private:
    std::string name;
public:
    Foo() : name("default"){}
    Foo(std::string Name): name(Name) {}
    void Print() { std::cout << name << std::endl; }
};
int main ()
{
    Foo* foo = new Foo();
    foo->Print();
    delete foo;
    foo = new Foo("special");
    foo->Print();
    delete foo;
}

输出为:

default
special
是的。但我可以知道你是怎么想到这个问题的吗?你有错吗?