我只是試驗並創建自己的字符串類。 (主要是因爲有一些東西我想用諸如「toBase64」等自定義方法構建等等。無論如何,我想知道如何在使用& String [0]時訪問char *的私有成員。C++ - 用字符串[0]在類
我認爲你可以使用操作符重載,但我目前只把它當作字符串[0]返回char *。(我知道&是指針運算符)。
STRING.H
namespace CoffeeBeans
{
class _declspec(dllexport) Coffee_String
{
char* String;
int StringLength;
public:
Coffee_String();
Coffee_String(LPCSTR CString);
LPSTR operator[](int);
~Coffee_String();
};
}
String.cpp
#include "stdafx.h"
#include "String.h"
#include <Windows.h>
CoffeeBeans::Coffee_String::Coffee_String() {
this->String = nullptr;
this->StringLength = 0;
}
CoffeeBeans::Coffee_String::~Coffee_String() {
if (String != nullptr) {
delete[] this->String;
this->String = nullptr;
this->StringLength = 0;
}
}
CoffeeBeans::Coffee_String::Coffee_String(LPCSTR CString) {
int StringLength = strlen(CString) + 1;
this->String = new char[StringLength]();
this->StringLength = StringLength - 1;
memcpy_s(this->String, StringLength, CString, StringLength);
}
LPSTR CoffeeBeans::Coffee_String::operator[](int)
{
return this->String;
}
Main.cpp的
case WM_CREATE:{
CoffeeBeans::Coffee_String String("Test");
//I want to be able to do
//strcpy_s(&String[0], 3, "hi"); //Copy "hi" into the private variable char*String.
//I know this isn't a practical use, I wanted quick example (I would really pass it to recv (WinSock2))
MessageBeep(0);
break;
}
什麼是你的問題經歷? – 0x499602D2
所有這些都是噪音。擺脫他們。在析構函數中,你不需要測試'String'是否爲NULL; '刪除'處理就好了。而在析構函數中,將'String'設置爲NULL並將'StringLength'設置爲0沒有意義;物體正在消失,沒有人能看到這些值。 –
@PeteBecker好吧我會從我的析構函數中刪除它,而我剛從我的書中教導,使用this->是一個好習慣,因爲它知道你指的是那個對象等。 –