我很满意operator =,它由编译器自动合成。但我希望它是私有的,并且不希望使用类型
的页面长定义来膨胀我的代码Foo& Foo::operator= (const Foo& foo)
{
if (this == &foo)
return *this;
member1_ = foo.member1_;
member2_ = foo.member2_;
member3_ = foo.member2_;
...
member1000_ = foo.member1000_;
return *this;
}
拜托,有办法吗?
答案 0 :(得分:8)
在C ++ 11中它是:
class Foo
{
Foo& operator=(const Foo& source) = default;
public:
// ...
};
不幸的是,大多数编译器还没有实现新标准的这一部分。
答案 1 :(得分:1)
另一种选择是使用Pimpl习语。
class Foo {
public:
Foo() : pImpl(new FooImpl) {}
// ... Foo's public interface, same as before
private:
Foo& operator=(const Foo& source); //- Foo's assignment operator is private
struct FooImpl;
boost::scoped_ptr<FooImpl> pImpl;
};
struct FooImpl {
// ... all the private data members that use to be in Foo
// Note: using the compiler generated copy assignment operator
};
复制赋值运算符是Foo客户端POV的私有运算符,但您仍然可以通过FooImpl利用编译器生成的复制赋值。在实现Foo的成员函数时需要权衡,因为您现在必须通过pImpl指针访问数据。