如何使用重载构造函数创建两个动态对象?
请看下面的代码,这是一个简单的主题,但我不知道。
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;
}
我的问题是,如何使用重载构造函数创建两个动态对象?
Please look the code below, it's a simple subject but I don't know.
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;
}
My question is, how can I create two dynamic objects with overloaded constructor?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
内置数组不可能实现这一点
但是请考虑使用 std::vector
这有一个额外的好处,你不需要担心内存管理
添加一个丑陋的解决方案,因为 OP 显然想要它。在创建数组之前将 FOO 设置为适当的值。 请在投反对票之前阅读评论
This is not possible with an built in array
However consider using a std::vector
This has the added benefit that you don't need worry about memory management
Adding an ugly solution because OP apparently wants it. Set FOO to appropriate value before creating the array. Please read comments before downvoting
数组在 C++98/03 中是有问题的,因为通常不能完全自由地初始化它们。 C++11 通过统一初始化修复了这个问题。现在你可以说,
Arrays are problematic in C++98/03, because you can't generally initialize them entirely freely. C++11 fixes this through uniform initialization. Now you can say,
在 C++ 中没有语法方法可以做到这一点,如这个(不正确的)示例所示:
试验 *TrialPtr2 = 新试验2;
如果您想使用数组,则必须执行“for”循环:
There is no syntactic way to do this in C++, as in this (incorrect) example:
trial *trialPtr2 = new trial2;
You must do a "for" loop if you wish to use an array: