C ++对象声明,没有默认构造函数(用户声明或隐式声明)

时间:2019-01-18 02:55:00

标签: c++ constructor default

如果我有

class Something
{
public:
    Something(int whatever) : whatever_(whatever) {}
private:
    int whatever_;
}

然后在堆栈上创建对象时会发生什么事

Something something;

因为没有默认构造函数?

1 个答案:

答案 0 :(得分:1)

在合格的编译器上,您会遇到编译错误。

以下代码:

class Something
{
public:
    Something(int whatever) : whatever_(whatever) {}
private:
    int whatever_;
};

Something something;

使用gcc8.2进行编译时会导致以下编译错误:

<source>:9:11: error: no matching function for call to 'Something::Something()' 
 Something something;
           ^~~~~~~~~    
<source>:4:5: note: candidate: 'Something::Something(int)'    
     Something(int whatever) : whatever_(whatever) {}    
     ^~~~~~~~~    
<source>:4:5: note:   candidate expects 1 argument, 0 provided    
<source>:1:7: note: candidate: 'constexpr Something::Something(const Something&)'    
 class Something    
       ^~~~~~~~~    
<source>:1:7: note:   candidate expects 1 argument, 0 provided    
<source>:1:7: note: candidate: 'constexpr Something::Something(Something&&)'    
<source>:1:7: note:   candidate expects 1 argument, 0 provided    
Compiler returned: 1

可通过godbolt获得实时示例。