简体   繁体   English

在C ++中,将基类计数为复制构造函数的构造函数是什么?

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

For example: 例如:

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. Does the constructor shown count as a copy constructor? 显示的构造函数是否算作复制构造函数?
  2. Does the assignment operator shown count as a copy assignment operator? 赋值运算符是否显示为复制赋值运算符?

Does the constructor shown count as a copy constructor? 显示的构造函数是否算作复制构造函数?

No. It does not count as a copy constructor . 不是 ,它不会算作一个拷贝构造函数
It is just a conversion constructor not a copy constructor. 它只是一个转换构造函数而不是复制构造函数。

C++03 Standard Copying class objects Para 2: C ++ 03标准复制类对象 第2段:

A non-template constructor for class X is a copy constructor if its first parameter is of type X& , const X& , volatile X& or const volatile X& , and either there are no other parameters or else all other parameters have default arguments. 如果X类的第一个参数是X&const X&volatile X&const volatile X& ,并且没有其他参数或者所有其他参数都有默认参数,则类X非模板构造函数是一个复制构造函数。


Does the assignment operator shown count as a copy assignment operator? 赋值运算符是否显示为复制赋值运算符?

No, it doesn't. 不,它没有。

C++03 Standard 12.8 Copying class objects Para 9: C ++ 03 Standard 12.8复制类对象 第9段:

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X , X& , const X& , volatile X& or const volatile X& . 用户声明的复制赋值运算符X::operator=是类X的非静态非模板成员函数,其中只有一个参数类型为XX&const X&volatile X&const volatile X&


Online Sample: 在线样本:

#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;
}

Output: 输出:

In conversion constructor
In doSomething
In operator=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM