是否可以在 C++ 中声明 operator= private 并同时由编译器合成它?
我对运算符 = 很满意,它是由编译器自动合成的。但我希望它是私有的,并且不想用类型的页面长定义来膨胀我的代码
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;
}
,有没有办法做到这一点?
I am happy with the operator =, which is synthesized by the compiler automatically. But I want it to be private and do not want to bloat my code with page long definitions of the type
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;
}
Please, is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
じ违心2025-01-04 17:11:11
另一种选择是使用 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 指针访问数据。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
在 C++11 中是:
不幸的是,大多数编译器还没有实现新标准的这一部分。
In C++11 it is:
Unfortunately, most compilers haven't implemented this part of the new standard yet.