c++ - 复制构造函数,子类
问题描述
一些帮助检查我的代码的正确性。
我正在使用来自 Mother 类的 Copy Constructor 复制 Child 对象,这是正确的吗?或者,我是否应该为 Child 实现一个复制构造函数?
#include <iostream>
class Mother{
public:
Mother(int data):member(data){
}
Mother(Mother const& mother):member(mother.member){
}
Mother& operator=(Mother const& mother){
if(this != &mother){
member=mother.member;
}
}
~Mother(){
}
friend std::ostream& operator<<(std::ostream& out, Mother const& mother){
out<<"Data :"<<mother.member<<std::endl;
return out;
}
protected:
int member;
};
class Child : public Mother{
public:
Child(int data):Mother(data){
}
~Child(){
}
private:
std::string chData;
};
int main()
{
int a(42);
Child child(a);
Child copyChild = Child(a);
std::cout<<copyChild;
return 0;
}
非常感谢。
解决方案
实际上,您正在使用子类的 CopyConstructor。即使您没有声明它,它也会在编译代码时隐式创建。
推荐阅读
- powershell - PowerShell 问题:将视频文件从硬盘驱动器上的单独文件夹移动到中央文件夹的脚本
- scala - 如何在数据框scala中的地图列类型上执行agg函数
- security - 安全上下文获取变量
- bash - 如何同时从多个目录中执行 SLURM 脚本?
- r - 如何重命名 R 中 SpatialPolygonsDataFrame 的特定列中的条目?
- javascript - 如何随机分配到治疗组进行在线网络学习?
- javascript - 如何在另一页中获取 json 数据?
- javascript - 在 StreamDeckSDK 中正确解析新行上的 Json 数组
- r - 与同事分享 R 闪亮应用程序的各种方式
- sql - 案例语法 - 减去 2 个值会给出不正确的数字