但是构造函数如何工作

but how do the constructor work?

本文关键字:工作 何工作 构造函数      更新时间:2023-10-16
#include <iostream>
using namespace std;
class A{
public:
    A(){cout << "A()" << endl; }
    A(string s): str(s){ cout << "A(" << str << ")" << endl; }
    ~A(){ cout << "delete!" << endl;}
    string str = "000";
};
int main(int argc, char** argv)
{
    //A a0;    // it will call A() by default
    A a1();    //even if i comment A(), the compiler will no warn me anything
    A a2("123");
    cout << a2.x << endl;
    return 0;
}

输出:

A(123)
123
delete!

所以,我只想知道为什么"A a1();"不能工作? 有人可以帮助我吗? 谢谢!

A a1(); 是一个函数原型,不带任何参数并返回 A