更新时间:2022-12-13 17:21:30
A n();
声明一个名为 n
的函数没有参数,并返回 A
。
因为它是一个声明,没有代码被调用/执行没有构造函数)。
在声明之后,你可能会写
A myA = n();
这将编译。但它不会链接!因为没有函数 n
的定义。
I am trying to understand how default constructor (provided by the compiler if you do not write one) versus your own default constructor works.
So for example I wrote this simple class:
class A
{
private:
int x;
public:
A() { std::cout << "Default constructor called for A\n"; }
A(int x)
{
std::cout << "Argument constructor called for A\n";
this->x = x;
}
};
int main (int argc, char const *argv[])
{
A m;
A p(0);
A n();
return 0;
}
The output is :
Default constructor called for A
Argument constructor called for A
So for the last one there is another constructor called and my question is which one and which type does n have in this case?
A n();
declares a function, named n
, that takes no arguments and returns an A
.
Since it is a declaration, no code is invoked/executed (especially no constructor).
After that declaration, you might write something like
A myA = n();
This would compile. But it would not link! Because there is no definition of the function n
.