我有以下問題: 在myClass中,我想默認初始化一個指向yourClass的指針,並帶有一個新的yourClass地址。 不幸的是,如果我想在任何點刪除指針,我會得到一個(核心轉儲)。C++默認構造函數,用新對象初始化指針
class myClass
{
protected:
yourClass * yc;
public:
myClass() { yc = new yourClass(); }
myClass(yourClass * tyc) { delete yc; yc = tyc; }
~myClass() { delete yc; yc = NULL; }
void setMyClass (yourClass * tyc) { delete yc; yc = tyc; }
void print() { yc->print(); }
};
int main()
{
yourClass b (//parameter);
myClass * a = new myClass();
a->print();
a->setMyClass(&b)
a->print();
delete a;
return 0;
}
a,的print()應該導致兩個不同的打印,具體取決於//參數。
我認爲你的類yc;而不是yourClass * yc,但我想知道它是否可能。
編輯: 我以下面的方式重新編寫代碼,它的工作原理。看起來很複雜,聰明的指針似乎很有希望,我仍然沒有應用「三大規則」。 這裏的代碼。謝謝大家。
class myClass
{
protected:
yourClass * yc;
bool dynamic;
public:
myClass() { dynamic = true; yc = new yourClass(); }
myClass (yourClass * tyc)
{
// dynamic init (like default)
if (tyc == NULL) { dynamic = true; yc = new yourClass(); }
// static use of yc
else { dynamic = false; yc = tyc; }
}
// because only if dynamic is true, we need to erase
~blu() { if (dynamic) { delete yc; dynamic = false; } }
void setMyClass(yourClass* tyc)
{
// leaving unchanged if new-stuff is NULL or like old-stuff
if (tyc == yc || tyc == NULL) return;
else // treating dynamic and static differently
{
if (dynamic) // if flag is set, must be deleted
{
delete yc; yc = tyc; dynamic = false;
}
else // must not be deleted, dynamic is still false
{
yc = tyc;
}
}
}
void print() { yc->print(); }
};
這應該是可能的 - 你的類的析構函數包含什麼? – 1615903
哦,我不認爲應該在參數化的構造函數中刪除yc。 – 1615903