如何解决派生类的五个规则
我一直在试图理解应该如何为派生类编写“五个规则”。我在网上发现的唯一内容就是应该如何为基类编写它。因此,在class A
之后给出class B
应该如何编写?
class A {
int a;
std::vector<int> k;
int *z;
public:
int getA() const {return a;}
std::vector<int> getK() const {return k;}
int* getZ() const {return z;};
A(int a,std::vector<int> k,int* z) : a(a),k(k),z(z) {}
A(const A& Other) : a(Other.getA()),k(Other.getK()),z(Other.getZ()) {}
A(A&& Other) : a(Other.getA()),k(std::move(Other.getK())),z(std::move(Other.getZ())) {}
A& operator=(const A& Other) {
return *this = A(Other);
}
A& operator=(A&& Other) {
a = Other.getA();
k = std::move(Other.getK());
z = std::move(Other.getZ());
return *this;
}
};
class B : public A {
char* t;
public:
char* getT() const {return t;}
B(int a,int* z,char* t) : A(a,k,z),t(t) {}
};
EDIT#1
谢谢大家的评论。是的,我知道我错过了析构函数。我忘了复制它,但是对我来说它并不重要。
让我重新表达一下我的主要担忧-例如B的复制构造函数是什么样子?常规构造函数包含class A
构造函数。 B的复制构造函数是否也应该有一些class A
的复制构造函数?看起来怎么样?那会在初始化列表中吗?
解决方法
对于派生类,您可以重用copy的基部,并移动基类中定义的构造函数/赋值运算符,而仅添加在派生类中添加的内容。
在展示之前,我对基类进行了一些更正,因为它实际上没有移动。我还建议不要使用 getter 方法实现此目的。直接寻找所需的资源。
https://contract.ibkr.info/index.php?action=Details&site=GEN&conid=48811132
现在进入答案部分-如何重用在#include <utility>
class A {
int a;
std::vector<int> k;
int *z;
public:
// getters removed - not needed for this example
A(int a,std::vector<int> k,int* z) : a(a),k(std::move(k)),z(z) {}
// rule of 5 start
A(const A& Other) : a(Other.a),k(Other.k),z(Other.z) {
// note that z can't be an owning pointer in this example
}
// actually move the content of the vector and exchange the pointer
// in the moved from object with a nullptr
A(A&& Other) :
a(Other.a),k(std::move(Other.k)),z(std::exchange(Other.z,nullptr))
{}
A& operator=(const A& Other) {
if(this == &Other) return *this; // don't do anything if self-assigning
return *this = A(Other); // this uses the move assignment operator
}
A& operator=(A&& Other) {
if(this == &Other) return *this;
a = Other.a;
std::swap(k,Other.k); // swap content,let Other destroy it
std::swap(z,Other.z); // not important since it's not an owning pointer
return *this;
}
~A() = default; // ... as z is not an owning pointer
// rule of 5 end
};
中已经定义的内容:
A
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。