如果我有
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/