gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 02:41:23 31 4
gpt4 key购买 nike

好吧,我理解我将获得一些随机值的部分,但是代码段中的 Foo() 构造函数是否就像我们没有构造函数时编译器提供的默认公共(public)构造函数一样定义?

#include<iostream>
using namespace std ;

class Foo{
int i ;
public:
Foo(){
}
void disp(){
cout<<"i = "<<i ;
}
};

int main(){
Foo bar1,bar2 ;
bar1.disp();
cout<<"\n";
bar2.disp();
}

我见过有人写这样一个空的构造函数,但我不明白为什么/什么时候使用它?

最佳答案

不带参数、不带 ctor-init-list 且主体为空的用户定义构造函数与默认构造函数的行为几乎相同。
不过有一个区别,它永远不会算作一个普通的 ctor!

像这样显式默认将避免这种差异和随之而来的潜在性能下降:

Foo() = default; // Needs C++11

What does "default" mean after a class' function declaration?

另见 <type_traits>检测差异的简单方法:http://en.cppreference.com/w/cpp/types/is_constructible

关于c++ - C++ 中的空构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25873281/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com