在 C++ 中,你可以通過繼承 std::string 類并重寫 length() 成員函數來定制 length() 函數。下面是一個示例:
#include <iostream>
#include <string>
class MyString : public std::string {
public:
// 重寫 length() 函數
size_t length() const {
size_t customLength = 0;
// 在這里添加你的自定義邏輯
// 例如,計算字符串中的某個特定字符的出現次數
for (char ch : *this) {
if (ch == 'a') {
customLength++;
}
}
return customLength;
}
};
int main() {
MyString myStr = "hello world";
std::cout << "自定義 length 函數的結果: " << myStr.length() << std::endl; // 輸出:自定義 length 函數的結果: 3
return 0;
}
在這個示例中,我們創建了一個名為 MyString 的類,它繼承自 std::string 類。我們重寫了 length() 函數,使其計算字符串中字符 ‘a’ 的出現次數。在 main() 函數中,我們創建了一個 MyString 對象,并調用自定義的 length() 函數。