0
点赞
收藏
分享

微信扫一扫

C++学习------类的五种构造函数

引言

C++中最重要的特性就是类与其继承,在类中,构造函数占据了重要的地位,今天我们就来一起研究一下C++中的五种构造函数,及其对应的用法。

C++中的五种构造函数

接下来我们都以复数类作为演示的基本类,复数包含实部与虚部,可以进行相应的初始化操作。

默认构造函数

定义:未提供显式初始值时,用来创建对象的构造函数,即无参构造函数。

Complex();

Complex::Complex() : real(0.0), imag(0.0){
std::cout << "default constructor" << std::endl;
}

//使用
Complex a;

普通构造函数

定义:用于构建类的新对象时调用的函数,一般是有参数的

Complex(double r, double i);

Complex::Complex(double r, double i) : real(r), imag(i){
std::cout << "normal constructor" << std::endl;
}

//使用
Complex b(3, 4);

复制构造函数

定义:出现对象拷贝时调用的构造函数。 复制构造函数在以下三种情况下会被调用

  • 当用一个对象去初始化同类的另一个对象时,会引发复制构造函数被调用。如:Complex c2(c1);Complex c2 = c1
  • 函数使用对象作为作为形参,则调用函数时,对应类的复制构造函数被调用。
  • 函数返回值使用对象,则函数返回时,对应类的复制构造函数被调用

Complex(const Complex& c);

Complex::Complex(const Complex& c) : real(c.real), imag(c.imag){
std::cout << "copy constructor" << std::endl;
}

//使用
Complex c(b);
Complex c = b;

void func1(Complex c){...}
func1(c);

Complex func2(){
Complex temp;
...
return temp;
}
c = func2();

转换构造函数

定义:构造函数接收一个不同于其类类型的形参,可以视为将其形参转换成类的一个对象。

Complex(double r);

Complex::Complex(double r) : real(r), imag(0.0){
std::cout << "convert constructor" << std::endl;
}

//使用
Complex d = 5.3;

移动构造函数

定义:以移动而非深拷贝的方式初始化含有指针成员的类对象,通常在使用临时对象初始化对象时,将临时对象的内存资源移为己有。 这里参考std::string的例子

​​www.aospxref.com/android-12.…​​

785     __compressed_pair<__rep, allocator_type> __r_;

1869 template <class _CharT, class _Traits, class _Allocator>
1870 inline
1871 basic_string<_CharT, _Traits, _Allocator>::basic_string(basic_string&& __str)
1872 #if _LIBCPP_STD_VER <= 14
1873 _NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value)
1874 #else
1875 _NOEXCEPT
1876 #endif
1877 : __r_(_VSTD::move(__str.__r_))//这里针对外部传入的数据做了move操作,接管了对应的内存空间
1878 {
1879 __str.__zero();
1880 #if _LIBCPP_DEBUG_LEVEL >= 2
1881 __get_db()->__insert_c(this);
1882 if (__is_long())
1883 __get_db()->swap(this, &__str);
1884 #endif
1885 }

举报

相关推荐

0 条评论