使用 () 创建类的实例
我有一个问题:在 C++ 中使用 ClassName instance()
创建类的实例时,使用什么构造函数?
示例:
#include <iostream>
using namespace std;
class Test
{
private:
Test()
{
cout << "AAA" << endl;
}
public:
Test(string str)
{
cout << "String = " << str << endl;
}
};
int main()
{
Test instance_1(); // instance_1 is created... using which constructor ?
Test instance_2("hello !"); // Ok
return 0;
}
谢谢!
I have a question : what constructor is used when you create an instance of a class with ClassName instance()
in C++ ?
Example:
#include <iostream>
using namespace std;
class Test
{
private:
Test()
{
cout << "AAA" << endl;
}
public:
Test(string str)
{
cout << "String = " << str << endl;
}
};
int main()
{
Test instance_1(); // instance_1 is created... using which constructor ?
Test instance_2("hello !"); // Ok
return 0;
}
Thanks !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
棘手!您可能会期望编译失败,因为默认构造函数是私有的。然而,它编译并没有创建任何东西。原因是什么?
...只是一个函数声明! (它返回
Test
并且不执行任何操作。)Tricky! You would expect compilation to fail as default constructor is private. However, it compiles and nothing is created. The reason?
... is just a function declaration! (Which returns
Test
and takes nothing.)语句
Test instance_1();
根本不调用构造函数,因为它没有定义变量 - 相反,它声明了一个名为instance_1
的函数,该函数返回一个对象输入测试
。要使用 0 参数构造函数创建实例,您可以使用Test instance_1;
。The statement
Test instance_1();
doesn't call a constructor at all, because it's not defining a variable - instead, it's declaring a function calledinstance_1
that returns an object of typeTest
. To create an instance using the 0-argument constructor, you'd useTest instance_1;
.