[英]Compare two objects of the same type for equality without public getters?
我有一個有幾個成員的班級。 到目前為止,我成功地在課堂上沒有吸氣員,因為我不希望人們暴露出班級的具體細節。 然后我不得不比較這個類的兩個對象是否相等。 我想不出創造幾個公共吸氣劑的方法。 我真的不想這樣做以保持封裝。 還有另外一種方法嗎?
class Foo
{
public:
bool Equals( const Foo &other ) const;
private:
bool x;
// lots of other members
};
bool Foo::Equals( const Foo &other ) const
{
// would I have to create and use public function other.GetX()?
}
您可以創建自己的公共平等成員運算符:
class Foo
{
public:
bool operator ==(Foo const& rhs) const
{
return x == rhs.x;
}
};
使用示例:
Foo a, b;
assert(a == b);
@ 0x499602D2已經給出了一個很好的答案,解釋了如何做到這一點。
為了補充這一點,我認為你尚未提到的關鍵點是訪問說明符( protected
和private
)適用於類級別,而不是實例級別。 因此,類的一個實例可以訪問另一個實例的私有成員。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.