
这不是写“ fen”一词有多少种方法的问题. 这是对您的基本水平的真实考验.
默认构造函数
是具有0个参数的构造函数. 此构造函数很特殊. 如果未在类中显式定义构造函数,则编译器将自动为您生成不带参数的默认构造函数. 默认构造函数不仅仅是概念上的事情. 对于具有自己的构造函数的类中的数据成员,默认的构造函数是依次调用这些成员的构造函数.
2. 复制构造函数

编译器为您提供了一个自动生成的用于复制对象的构造函数. 就像默认构造函数一样,复制构造函数也可以执行某些操作.
3. 移动构造函数
与上述类似,因此我不再赘述.
可以将默认,复制和移动构造函数与您定义的其他构造函数不同的原因分开并列出,因为它们是编译器可以自动生成函数主体的构造函数. 在C ++中,默认构造,复制构造和移动构造具有特殊的语法含义.

4. 继承构造函数,即使用using Base :: Base;直接继承基类构造函数的语句
struct Base
{
int x;
int y;
Base(int x, int y) : x(x), y(y)
{
}
};
struct Derived: Base
{
using Base::Base;
};
int main()
{
Derived d(3, 4);
}
在C ++ 11之前,您必须在Derived中编写另一个具有相同参数列表的构造函数c++类构造函数,以将参数转发给基类.
struct Base
{
int x;
int y;
Base(int x, int y) : x(x), y(y)
{
}
};
struct Derived: Base
{
Derived(int x, int y) : Base(x, y)
{
}
};
int main()
{
Derived d(3, 4);
}

如果基类有许多重载的构造函数,则必须在子类中重写每个重载的版本,这违反了代码重用的原则!更糟糕的是,如果重构了基类的构造函数,但是子类却忘记了遵循,那么BOOM很容易
struct Base
{
int x;
int y;
Base(int x, double y) : x(x), y(y) // 基类 api 改了
{
}
};
struct Derived: Base
{
Derived(int x, int y) : Base(x, y) // 子类这里忘改了
{
}
};
int main()
{
Derived d(3, 4.5); // 定义变量的时候参考了基类 api 手册
// 你就等着调 bug 调到猝死吧
}
还有一件事情,使用Base ::基类方法名称的语法包含在C ++ 98中,而不是C ++ 11中添加的新事物.
#include <iostream>
class Base
{
protected:
void print() const
{
std::cout << 2333 << std::endl;
}
};
class Derived: public Base
{
public:
using Base::print;
// 如果不加这句声明,
// 则 print 方法在 Derived 类中就仍是 protected 的
// main 中无法调用
};
int main()
{
Derived d;
d.print();
}

如上面的示例所示,此语法可以更改方法的访问控制域c++类构造函数,例如公开基类的保护方法. 当然,您也可以在子类中将基类的public方法更改为private方法. 同样,这是C ++ 98中可用的语法. 只是在98中不允许使用使用父类class :: constructor(在某种意义上,构造函数也是该类的方法,对,所以添加了11)
5. 委托构造函数
我们知道在Java中,您可以使用this关键字来调用此类的其他重载版本的构造函数:
class Base
{
public int x;
public int y;
public Base(int x, int y)
{
this.x = x;
this.y = y;
}
public Base()
{
this(0, 0);
}
}
C ++ 11的委托构造函数与此类似:
class Base
{
public:
int x;
int y;
Base(int x, int y) : x(x), y(y)
{
}
Base() : Base(0, 0)
{
}
};
没有此语法的语法缺点与上面相同,违反了代码重用+调试和突然死亡的原则.
加上您提到的常规构造函数,恰好有六个.
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/jisuanjixue/article-288946-1.html
蛆是苍蝇的幼虫