使用 () 创建类的实例

发布于 2024-11-25 11:33:08 字数 515 浏览 3 评论 0原文

我有一个问题:在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

远昼 2024-12-02 11:33:08

棘手!您可能会期望编译失败,因为默认构造函数是私有的。然而,它编译并没有创建任何东西。原因是什么?

Test instance_1();

...只是一个函数声明! (它返回 Test 并且不执行任何操作。)

Tricky! You would expect compilation to fail as default constructor is private. However, it compiles and nothing is created. The reason?

Test instance_1();

... is just a function declaration! (Which returns Test and takes nothing.)

夏尔 2024-12-02 11:33:08

语句 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 called instance_1 that returns an object of type Test. To create an instance using the 0-argument constructor, you'd use Test instance_1;.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文