使用const成员的交换方法 [英] Swap method with const members
问题描述
我想为我的类(让我们称之为A)实现一个Swap()方法来做复制和交换operator =()。据我所知,swap方法应该通过交换类的所有成员来实现,例如:
class A
{
public:
void swap(A& rhv)
{
std :: swap(x,rhv.x);
std :: swap(y,rhv.y);
std :: swap(z,rhv.z);
}
private:
int x,y,z;
};
但是如果我有一个const成员应该怎么办?我不能调用std :: swap为它,所以我不能代码A :: Swap()。
编辑:其实我的类有点复杂。我想序列化和反序列化它。 Const成员是一个不会在此对象内更改(例如其ID)的数据。所以我在想如何写:
class A
{
public:
void Serialize(FILE * file)const
{
fwrite(& read_a,1,sizeof(read_a),file);
}
void Deserialize(FILE * file)const
{
size_t read_a;
fread(& read_a,1,sizeof(read_a),file);
A tmp(read_a);
this-> Swap(tmp);
}
private:
const size_t a;
};
并调用此代码:
A a;
FILE * f = fopen(...);
a.Deserialize(f);
对于这种含糊的措辞,我很抱歉。
经过一个好的睡眠后,我认为最好的答案是使用一个非const指针指向一个const值 - 所有这些都是你要捕获的语义。 / p>
I want to implement a Swap() method for my class (let's call it A) to make copy-and-swap operator=(). As far as I know, swap method should be implemented by swapping all members of the class, for example:
class A
{
public:
void swap(A& rhv)
{
std::swap(x, rhv.x);
std::swap(y, rhv.y);
std::swap(z, rhv.z);
}
private:
int x,y,z;
};
But what should I do if I have a const member? I can't call std::swap for it, so I can't code A::Swap().
EDIT: Actually my class is little bit more complicated. I want to Serialize and Deserialize it. Const member is a piece of data that won't change (its ID for example) within this object. So I was thinking of writing something like:
class A
{
public:
void Serialize(FILE* file) const
{
fwrite(&read_a, 1, sizeof(read_a), file);
}
void Deserialize(FILE* file) const
{
size_t read_a;
fread(&read_a, 1, sizeof(read_a), file);
A tmp(read_a);
this->Swap(tmp);
}
private:
const size_t a;
};
and call this code:
A a;
FILE* f = fopen(...);
a.Deserialize(f);
I'm sorry for such vague wording.
After a good nights sleep I think the best answer is to use a a non-const pointer to a const value -- after all these are the semantics you are trying to capture.
这篇关于使用const成员的交换方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!