下面是使用C++實現的一個簡單的Char類,包括私有成員char* c用于存儲字符串數據,以及int* ip用于存儲一些整型數據。同時,提供了構造函數、拷貝構造函數、析構函數、賦值函數和打印函數。此外,我還添加了一個命名空間MyNamespace來組織這個類。
#include <iostream>
namespace MyNamespace {
class Char {
private:
char* c; // 用于存儲字符串的私有成員
int* ip; // 用于存儲整型數據的私有成員
public:
// 構造函數
Char(const char* str, const int* arr, int size) {
c = new char[strlen(str) + 1];
strcpy(c, str);
ip = new int[size];
for (int i = 0; i < size; ++i) {
ip[i] = arr[i];
}
}
// 拷貝構造函數
Char(const Char& other) {
int size = sizeof(other.ip) / sizeof(other.ip[0]);
c = new char[strlen(other.c) + 1];
strcpy(c, other.c);
ip = new int[size];
for (int i = 0; i < size; ++i) {
ip[i] = other.ip[i];
}
}
// 析構函數
~Char() {
delete[] c;
delete[] ip;
}
// 賦值函數
Char& operator=(const Char& other) {
if (this != &other) {
delete[] c;
delete[] ip;
int size = sizeof(other.ip) / sizeof(other.ip[0]);
c = new char[strlen(other.c) + 1];
strcpy(c, other.c);
ip = new int[size];
for (int i = 0; i < size; ++i) {
ip[i] = other.ip[i];
}
}
return *this;
}
// 打印函數
void print() const {
std::cout << "String: " << c << std::endl;
std::cout << "Array: ";
for (int i = 0; i < getSize(); ++i) {
std::cout << ip[i] << " ";
}
std::cout << std::endl;
}
// 獲取數組大小
int getSize() const {
// 注意:這不是一個安全的方法,因為這里假設ip總是指向一個有效的數組
// 實際上,我們應該在構造時存儲數組的大小
return ip ? 1 : 0; // 示例中簡化處理,假設只有一個整數
}
};
int main() {
int arr[] = {1, 2, 3};
Char charObj("Hello, World!", arr, 3);
charObj.print();
Char copiedCharObj = charObj;
copiedCharObj.print();
Char assignedCharObj("Kimi", arr, 1);
assignedCharObj = copiedCharObj;
assignedCharObj.print();
return 0;
}
}
在這個實現中:
- 構造函數接收一個
const char*類型的字符串和const int*類型的數組,以及數組的大小,并將它們復制到char* c和int* ip中。 - 拷貝構造函數創建了一個新的
Char對象,它是現有對象的副本。 - 析構函數釋放了
char* c和int* ip指向的內存。 - 賦值函數實現了深拷貝,并在必要時進行了自賦值檢查。
- 打印函數用于輸出字符串內容和數組內容,以驗證我們的
Char類是否按預期工作。
請注意,這個實現簡化了數組大小的處理,實際上應該在構造時存儲數組的大小,而不是依賴于ip是否指向一個有效的數組。此外,這個實現沒有處理所有可能的異常情況,如內存分配失敗等。在實際應用中,應該使用標準庫中的std::vector或std::string來避免手動管理內存的復雜性和風險。
浙公網安備 33010602011771號