构造函数没有return类型,但为什么这部分编译正常?

Constructor does not have a return type, but why this part compiles normally?

A Constructors 没有 return 类型,但我想知道为什么这段代码可以正常编译?

这是代码示例

class B
{
public:
   int c;
   int b;
public:
   B(){c = 5; b = 10; std::cout << "B ctor" << std::endl;}
};

B b = B();                                //  this part ?
std::cout << "a=: " << b.a << std::endl;
// or the same
//B* ptr;
//*(B*)ptr = B();
//std::cout << "a=: " << ptr->c << std::endl;

构造函数具有隐式 return 类型,即由该构造函数构造的对象。

B();  // you are constructing an object and not using it anyway
B b = B(); // you are constructing an object and assigning it to variable b, so that you can use it.

因此,构造函数以 return *this 结束。

在构造函数中,您正在处理一个已分配但未初始化的对象,您必须构造它(initialize/construct 实例变量)。 构造函数调用的结果(如调用者所见)是一个功能完备的对象,可以使用。