如何使用重载构造函数创建两个动态对象
how can I create two dynamic objects with overloaded constructor?
请看看下面的代码,这是一个简单的主题,但我不知道。
class trial{
public:
trial(){
y = -1;
}
trial(int x){
y = x;
}
public:
int y;
};
int main() {
trial *trialPtr = new trial(); // creates a dynamic object with empty constructor
trial *trialPtr1 = new trial(1); // creates a dynamic object with overloaded constructor
trial *trialPtr2 = new trial[2]; // creates two dynamic objects with empty constructor
return 0;
}
我的问题是,如何用重载构造函数创建两个动态对象?
对于内置数组
是不可能的但是考虑使用std::vectorvector<trial> var(10, trail(4));
这有一个额外的好处,你不需要担心内存管理
添加一个丑陋的解决方案,因为OP显然想要它。在创建数组之前,将FOO设置为合适的值。请在拒绝投票前阅读评论
int FOO = -1;
class trial{
public:
trial(){
y = FOO;
}
trial(int x){
y = x;
}
public:
int y;
};
int main(int argc, _TCHAR* argv[])
{
FOO = 4;
trial *trialPtr2 = new trial[2];
return 0;
}
数组在c++ 98/03中是有问题的,因为通常不能完全自由地初始化它们。c++ 11通过统一初始化解决了这个问题。现在你可以说
new trial[2] { 1, 1 };
在c++中没有语法方法可以做到这一点,就像下面这个(不正确的)示例:*trialPtr2 = new trial2;如果您希望使用数组,则必须执行for循环:
trial *trialPtr2[] = new (*trial)[2];
for (int i = 0; i < 2; i++)
{
trialPtr2[i] = new trial(3);
}
相关文章:
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 类型测试对象的动态数组的这两个声明之间的区别?
- 为什么动态分配的两个变量的内存位置不是连续的?
- 从两个或多个不同的动态数组中查找缺失的 int 值
- 动态创建 std::string 时的两个"新"调用
- 在打印出动态分配的数组中的前两个数字时遇到问题,其他数字工作正常
- 在 C++ 中创建动态数组并返回两个值
- 具有两个动态维度和一个静态维度的多维数组
- 为两个动态数组赋值
- 如何在两个动态生成的组合蛋白上使用不同的值
- C++ 类两个动态属性
- 连接两个动态字符串数组
- 尝试在 c++ 中将两个动态创建的矩阵(2d 向量)相乘
- 我计算两个动态数组乘积的函数不起作用
- 如何在C++中将文本文件读入两个动态向量
- 动态数组:将中两个动态数组中元素的值添加到新的动态数组中
- 给定两个动态的rxc矩阵,我如何交错行来产生一个2rxc矩阵
- 如何使用重载构造函数创建两个动态对象
- 如何比较两个动态数组并检查哪些元素匹配
- 两个动态数组导致内存分配错误