将 new 运算符与对象的非默认构造函数一起使用
Using the new operator with an object's non-default constructor
想要什么:
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
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 初始化具有非默认构造函数的std::数组项的更好方法
- 具有默认模板类型的默认构造函数的类型推导
- 如何使用非默认构造函数实例化模板化类
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 有没有一种代码密度较低的方法来使用非默认构造函数初始化数组?
- 声明没有默认构造函数的字段
- 基类中的默认析构函数禁用子类中的移动构造函数(如果有成员)
- 没有默认构造函数作为模板参数的自定义比较器
- C++17 没有默认构造函数的地图放置(私有默认构造函数)
- 使用移动调用对等构造函数unique_ptr默认构造函数
- C++复制构造函数和默认构造函数
- 将向量从 N1 缩小到 N2 项,而不触发默认构造函数并仅使用 move 语义
- 构造函数默认公共和私有变量
- 类模板构造函数默认参数
- 构造函数默认参数
- C++模板构造函数默认参数
- 在c++中设置构造函数默认值
- c++构造函数默认参数
- C++构造函数默认值头文件