[英]c++ Encapsulation questions
我試圖使用std :: sort與自定義比較功能。 為此,我有一個名為trySort
的類。 這是trySort
類的示例代碼:
trySort.h
class trySort {
public:
private:
std::string sortThis;
};
trySort.cpp
bool sortThisAsc (const trySort & rhs , const trySort & lhs) {
return lhs.sortThis > rhs.sortThis;
}
如果成員sortThis
是私有的,這將拋出一個錯誤。
如果我做sortThis
的公共成員......
trySort.h
class trySort {
public:
std::string sortThis;
private:
};
trySort.cpp
bool sortThisAsc (const trySort & rhs , const trySort & lhs) {
return lhs.sortThis > rhs.sortThis;
}
......它會奏效。 好像我把sortThis
是一個公共成員。
所以我的問題是:如果我這樣做,我是不是封裝了我的數據?
如果是這樣,除了將其作為公共成員之外,還有哪些其他可能的方法?
您可以將operator >
添加到trySort
類。
trySort.h
class trySort {
public:
bool operator >(trySort const &other) {
return sortThis > other.sortThis;
}
private:
std::string sortThis;
}
如果你需要更多的靈活性(一些其他類型的比較),只需使用getter函數封裝sortThis
。
trySort.h
class trySort {
public:
std::string const &getSortThis() const {
return sortThis;
}
private:
std::string sortThis;
}
如果您完全確定sortThis
將始終在項目過程中不可變,因此在構造函數中初始化,您可以將其保留為公共const成員,但在大多數情況下,這是非常推測的方法。
trySort.h
class trySort {
public:
trySort(std::string const sortThis)
: sortThis(sortThis) {
}
const std::string sortThis;
}
或者你可以和friend
一起做,但我會留下它作為最后的手段,因為在大多數情況下,它結果表明過度親密(總有一些其他方法可以避免使用friend
)。 在某些情況下使用friend
可能是合適的,但它絕不會破壞封裝,不同的是, friend
條款向班級客戶發出信號,說明破壞是故意的。
使用朋友:
class trySort {
friend bool sortThisAsc (const trySort & rhs , const trySort & lhs);
private:
std::string sortThis;
}
它只能訪問此功能,而不能訪問任何其他功能
編輯這擺脫了你提到的編譯錯誤,但只有非成員函數可以傳遞給std :: sort(),所以這不太有效。
在cpp文件中,更改函數定義
bool sortThisAsc (const trySort & rhs , const trySort & lhs) {
至
bool trySort::sortThisAsc(const trySort & rhs, const trySort & lhs) {
沒有trySort::
該函數未在trySort
類作用域中定義(即在該類之外),因此如果您嘗試訪問trySort
私有變量,編譯器會抱怨。
這樣,您可以將其保存為您最初要求的私有方法。
至少有兩種選擇。 例如,您可以向此數據成員聲明一個公共getter
class trySort {
public:
const std::string & get_string() const { return sortThis; }
private:
std::string sortThis;
}
然后在函數sortThisAsc中編寫
bool sortThisAsc (const trySort & rhs , const trySort & lhs) {
return lhs.get_string() > rhs.get_string();
}
或者您可以將該函數聲明為該類的友元函數
class trySort {
public:
friend bool sortThisAsc (const trySort & rhs , const trySort & lhs);
private:
std::string sortThis;
}
在這種情況下,函數定義不會更改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.