[英]Pointer Issues.. ( C++ )
就在我以為自己想通了的時候,我得到了異常處理錯誤。 問題:問題在於私有成員在構造函數之外丟失了信息。 這是我的班級定義
碼:
class ClassType
{
private:
char *cPointer;
int length;
public:
ClassType();
// default constr. needed when allocating in main.
ClassType( const ClassType* );
char otherFunc();
};
classtype.cpp:
"#include ClassType.h"
ClassType( const ClassType* )
{
cPointer = ClassType->cPointer;
length = ClassType->length;
}
ClassType::ClassType( const char *myVar )
{
cPointer = new char[ strlen( myVar ) + 1 ] //+1 for trailing '\0'
strcpy( cPointer, myVar );
length = strlen( cPointer );
}
char ClassType::otherFunc()
{
cPointer; // Nothing is shown when debugging..
cPointer = "MyPointer"; // Results in acrash
length = 5; // Results in a crash
}
// The main function is working properly.
ClassType(const ClassType& rhs)
我想不出為什么它會在您指示的位置崩潰,但是您的代碼存在一些問題(其中一些是編譯時問題,因此我們無法確定該代碼是否正確反映了問題):
ClassType::ClassType( const ClassType* )
,哪個ClassType
實例擁有cPointer
指向的對象? cPointer
可能指向由new
分配的內容,也可能沒有,因此您將難以確定應何時刪除由new
分配的內容。 就編譯時錯誤而言:
ClassType( const ClassType* )
的定義應以ClassType::ClassType( const ClassType* )
開頭 ClassType::ClassType( const ClassType* )
應使用參數而不是ClassType
類名作為指針 char ClassType::otherFunc()
需要一個返回語句 這是真實的代碼嗎?
ClassType( const ClassType* )
{
cPointer = ClassType->cPointer;
length = ClassType->length;
}
如果是這樣,則需要這樣:
ClassType( const ClassType* rhs )
{
cPointer = rhs->cPointer;
length = rhs->length;
}
另外,此構造函數不是默認的ctor:
ClassType( const ClassType* ); // default constr. needed when allocating in main.
默認ctor特別是采用零參數或所有參數都指定了默認值的ctor。 換句話說,默認ctor是可以這樣調用的ctor:
ClassType myObject;
在您對此代碼的其他問題中,我提供了一個非常完整的答案。 我相信主要的問題是您的副本構造函數被嚴重破壞。 這將導致雙重錯誤和其他缺陷。 同樣,由於析構函數調用會在分配的指針上刪除,因此您永遠無法將字符串文字分配給類指針。
默認構造函數是所有參數都具有默認值的構造函數,因此采用指針的構造函數不是默認構造函數。
您的崩潰位置表明該類的構造不正確,因此分配給它們時可能會遇到地址錯誤。
您能否發布main,因為那可能是解決問題的關鍵?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.