嘿,我刚刚在我的班级中实现了三巨头加上复制和交换习语赋值运算符。 但是,我有一些其他类继承了这个超类,现在我问自己是否应该 在子类中重新定义这个交换方法。
我应该在每个类中将交换方法设置为私有吗? 我应该将交换方法设为虚拟吗? 大家有什么建议?
Tyvm!
头文件:
超类:
#ifndef USER_H
#define USER_H
#include <string>
class user
{
public:
explicit user();
//user(std::string&, const int);
user(std::string&, const int, std::string&, std::string&);
~user(){};
// Big three/four...
user(const user&); // Copy constructor
user(user&&); // move contructor
user& operator=(user); // Copy/Move assignment
// + destructor
// Swap function for move assignment
friend void swap(user& first, user& second)
{
std::swap(first.name_m, second.name_m);
std::swap(first.id_m, second.id_m);
std::swap(first.class_m, second.class_m);
std::swap(first.rights_m, second.rights_m);
}
virtual void printDescription() const;
void setName(const std::string&);
void setId(const int);
void setClass(const std::string&);
void setRights(const std::string&);
const std::string& getName() const;
const int getId() const;
const std::string& getClass() const;
const std::string& getRights() const;
protected:
std::string name_m;
int id_m;
std::string class_m;
std::string rights_m;
};
#endif
子类:
#ifndef USER_ADMIN_H
#define USER_ADMIN_H
#include "user.hpp"
#include <string>
struct properties_txt
{
std::string class_admin = std::string("admin");
std::string rights_admin = std::string("admin rights");
};
class user_admin : public user
{
public:
explicit user_admin();
user_admin(std::string&, const int);
user_admin(std::string&, const int, std::string&, std::string&);
~user_admin();
user_admin(const user_admin&);
user_admin(user_admin&&);
user_admin& operator=(user_admin);
// Swap function for move assignment
friend void swap(user& first, user& second) // Doesnt work obviously
{
std::swap(first.name_m, second.name_m);
std::swap(first.id_m, second.id_m);
std::swap(first.class_m, second.class_m);
std::swap(first.rights_m, second.rights_m);
}
void printDescription() const override;
private:
};
#endif
只是问什么是最好的
由于派生类不添加任何字段,因此它根本不应该提供自定义
swap
。将自动使用基类中的一个。
如果确实有额外的成员,则交换应该实施为:
using std::swap;
swap(static_cast<user &>(first), static_cast<user &>(second));
swap(first.extra, second.extra); // Only swap the fields added in the derived class.
其他一些事情:
operator=
和 swap()
都应该是 noexcept
。swap()
。隐式生成的就可以正常工作。std::move
它们。using std::swap; swap(...);
而不是直接调用 std::swap
的习惯可能是个好主意,以便能够使用自定义交换,而不必考虑是否需要为每种单独类型省略 std::
。