构造函数没有返回类型,但我想知道为什么这个代码部分正常编译?
这是代码示例
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;
答案 0 :(得分:1)
构造函数具有隐式返回类型,即由该构造函数构造的对象。
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
结尾。
在构造函数中,您正在处理已分配但未初始化的对象,并且您必须构造它(初始化/构造实例变量)。 构造函数调用的结果(由调用者看到)是一个可以使用的全功能对象。