在C++中,执行一个构造函数,该构造函数将基类计数作为复制构造函数

In C++, does a constructor that takes the base class count as a copy constructor?

本文关键字:构造函数 基类 复制 一个 执行 C++      更新时间:2023-10-16

例如:

class Derived : public Base
{
    Derived(const Base &rhs)
    {
        // Is this a copy constructor?
    }
    const Derived &operator=(const Base &rhs)
    {
        // Is this a copy assignment operator?
    }
};
  1. 显示的构造函数是否算作复制构造函数
  2. 显示的分配运算符是否算作复制分配运算符

显示的构造函数是否算作复制构造函数

没有。它不算作复制构造函数
它只是一个转换构造函数而不是复制构造函数。

C++03标准复制类对象 第2段:

如果类X的第一个参数类型为X&const X&volatile X&const volatile X&,并且没有其他参数,或者所有其他参数都有默认参数,则该类的非模板构造函数是复制构造函数。


显示的赋值运算符是否算作复制赋值运算符

不,不是。

C++03标准12.8复制类对象 第9段:

用户声明的复制赋值运算符X::operator=是类X的非静态非模板成员函数,仅具有一个类型为XX&const X&volatile X&const volatile X&的参数。


在线样本:

#include<iostream>
class Base{};
class Derived : public Base
{
   public:
    Derived(){}
    Derived(const Base &rhs)
    {
       std::cout<<"n In conversion constructor";
    }
    const Derived &operator=(const Base &rhs)
    {
        std::cout<<"n In operator=";
        return *this;
    }
};
void doSomething(Derived obj)
{
    std::cout<<"n In doSomething";
}
int main()
{
    Base obj1;
    doSomething(obj1);

    Derived obj2;
    obj2 = obj1;    
    return 0;
}

输出:

In conversion constructor
In doSomething
In operator=