在C++中,执行一个构造函数,该构造函数将基类计数作为复制构造函数
In C++, does a constructor that takes the base class count as a copy constructor?
例如:
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?
}
};
- 显示的构造函数是否算作复制构造函数
- 显示的分配运算符是否算作复制分配运算符
显示的构造函数是否算作复制构造函数
没有。它不算作复制构造函数
它只是一个转换构造函数而不是复制构造函数。
C++03标准复制类对象 第2段:
如果类
X
的第一个参数类型为X&
、const X&
、volatile X&
或const volatile X&
,并且没有其他参数,或者所有其他参数都有默认参数,则该类的非模板构造函数是复制构造函数。
显示的赋值运算符是否算作复制赋值运算符
不,不是。
C++03标准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;
}
输出:
In conversion constructor
In doSomething
In operator=
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 参数包构造函数在类模板中隐藏用户定义的转换
- 具有已删除移动和复制构造函数的类的就地构造
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- C++构造函数和类?
- 在 C++ 中,默认情况下构造函数为类的数据成员提供的值是多少?
- 如何在其他类中使用参数化构造函数制作类的对象?
- 具有值包装器的可变参数模板构造函数的类构造函数优先级
- 如何使用私有构造函数对类进行单元测试?
- C++虚拟函数:基类函数是调用的,而不是派生的
- c++17在编译时将带有已删除复制构造函数的类添加到std::vector
- 从作为模板参数传递给构造函数的类继承,或者从它们继承
- 继承的构造函数忽略类内初始化
- 模板和隐式构造函数的类定义之外的友元声明
- 具有字符串文本构造函数的类不适用于 const 引用初始化
- 为什么具有私有构造函数的类不阻止从此类继承?如何控制哪些类可以从某个基继承?
- 具有多个非默认构造函数基的Singleton派生类
- 调用基默认构造函数模板类
- 当基类未指定构造函数时,如何使用仅具有带参数的构造函数的类派生基类?
- 构造所有基类不需要默认生成的构造函数