C++ 对象声明和无默认构造函数(用户声明或隐式声明)

标签 c++ constructor default

如果我有

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

然后当我在栈上创建一个对象时会发生什么

Something something;

因为没有默认构造函数?

最佳答案

在符合规范的编译器上,您会遇到编译错误。

以下代码:

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 获得.

关于C++ 对象声明和无默认构造函数(用户声明或隐式声明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54247157/

相关文章:

c++ - C++ 类中的构造函数

c++ - C++中的延迟构造函数

c++ - 如何设置QPlainTextEdit的水平溢出?

c++ - QWidgets 是否为成员(member)?

c++ - 锁定时释放持有互斥锁的对象

javascript - 我可以在不使用 new 关键字的情况下构造 JavaScript 对象吗?

configuration - 更改 Hadoop 从节点上的默认配置?

C11 _Generic 用法

c++ - 使用 Hoare 分区的快速排序

c++ - 围绕 shared_ptr 构建对象系统