Mat*_*att 4 c++ inheritance copy-constructor copy-assignment
例如:
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?
}
};
Run Code Online (Sandbox Code Playgroud)
显示的构造函数是否算作复制构造函数?
号它不是算作一个拷贝构造函数.
它只是一个转换构造函数而不是复制构造函数.
C++ 03标准复制类对象 第2段:
如果类的非模板构造
X函数的第一个参数是type ,或,并且没有其他参数,或者所有其他参数都有默认参数X&,则它是一个复制构造函数.const X&volatile X&const volatile X&
赋值运算符是否显示为复制赋值运算符?
不,它没有.
C++ 03 Standard 12.8复制类对象 第9段:
用户声明的拷贝赋值运算符
X::operator=是类的非静态的非模板成员函数X与类型的只有一个参数X,X&,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;
}
Run Code Online (Sandbox Code Playgroud)
输出:
In conversion constructor
In doSomething
In operator=
Run Code Online (Sandbox Code Playgroud)