以下代码是允许
struct Foo {
int x;
};
Foo f;
Foo & f_ref = f;
(&f) -> ~Foo ();
new (&f) Foo ();
int x = f_ref .x;
Run Code Online (Sandbox Code Playgroud)
但下面的代码是不容许
struct Foo {
const int & x; // difference is const reference
Foo (int & i) : x(i) {}
};
int i;
Foo f (i);
Foo & f_ref = f;
(&f) -> ~Foo ();
new (&f) Foo (i);
int x = f_ref .x; …Run Code Online (Sandbox Code Playgroud) 我想为我的类实现一个Swap()方法(让我们称之为A)来创建copy-and-swap operator =().据我所知,交换方法应该通过交换类的所有成员来实现,例如:
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;
};
Run Code Online (Sandbox Code Playgroud)
但如果我有一个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;
};
Run Code Online (Sandbox Code Playgroud)
并调用此代码:
A a;
FILE* f = fopen(...);
a.Deserialize(f);
Run Code Online (Sandbox Code Playgroud)
对于这种模糊的措辞,我很抱歉.
我有以下代码
class a {
public:
const int aa;
a(int aa) : aa(aa){}
};
int main() {
std::vector<a> v;
v.emplace_back(1);
v.emplace_back(2);
v.emplace_back(3);
v.emplace_back(4);
std::iter_swap(v.begin() + 1, v.rbegin());
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试交换向量的两个元素时,我收到错误.
Error C2280 'a &a::operator =(const a &)': attempting to reference a deleted function
Run Code Online (Sandbox Code Playgroud)
我理解这是因为a有一个不变的成员,但我无法弄清楚如何使这个工作.