当我在线查看数学引擎向量的实现时,我看到了这段代码。
class R4DVector3n{
private:
public:
//x, y and z dimensions
float x;
float y;
float z;
//Constructors
R4DVector3n();
R4DVector3n(float uX,float uY,float uZ);
//Destructors
~R4DVector3n();
//Copy Constructors
R4DVector3n(const R4DVector3n& v);
R4DVector3n& operator=(const R4DVector3n& v);
};类存在多个构造函数的原因/用途是什么,以及作者所说的“复制构造函数”是什么意思。
发布于 2022-01-29 04:47:34
类存在多个构造函数的原因/用途是什么?
这样我们就可以使用不同的形式创建该类的实例。换句话说,对不同对象的成员变量进行不同的初始化。例如,对于类R4DVector3n,我们可以根据需求创建使用不同构造函数的实例,如下所示:
int main()
{
R4DVector3n obj1; //this creates an object named obj1 of type R4DVector3n using the default constructor
R4DVector3n obj2(1.1f,2.3f, 4.1f); //this creates an object named obj2 of type R4DVector3n using the Parameterized constructor
R4DVector3n obj3 = obj2; //this creates object named obj3 of type R4DVector3n using the copy constructor
}在上面的示例中,对象obj1是使用默认构造函数创建的。
对象obj2是使用参数化构造函数创建的。
对象obj3是使用复制构造函数创建的。
作者所说的“复制构造器”是什么意思?
来自复制构造函数文档
类T的复制构造函数是一个非模板构造函数,其第一个参数是
T&、const T&、volatile T&或const volatile T&,并且要么没有其他参数,要么其余参数都具有默认值。
当我们想要使用另一个对象创建一个对象时,这是非常有用的。因此,在您的代码片段中,您有以下复制构造函数:
R4DVector3n(const R4DVector3n& v); //this is a copy constructor上面的语句是类构造函数的声明。在我的示例中使用了这一点,当时我写道:
R4DVector3n obj3 = obj2; //this uses the copy constructor另外,请注意以下声明:
R4DVector3n& operator=(const R4DVector3n& v); //this is copy assignment operator上面的语句是声明,用于复制赋值算子。
https://stackoverflow.com/questions/70902305
复制相似问题