我是 C++ 新手,所以我正在尝试借助 Wikipedia 中的示例来学习它。我玩了一些类,我有一个分段错误错误。
这是我的代码:
class SomeClass {};
class AnotherClass {
SomeClass* sc
public:
AnotherClass(SomeClass* SC):( sc = SC; ){}
//***********************************************************************
~AnotherClass(){ delete sc; } //here I'm getting rid of internal pointer
//***********************************************************************
};
int main( int argc, char* argv[] ) {
SomeClass* SC = new SomeClass();
AnotherClass* AC = new AnotherClass(SC);
delete AC;
// *****************************************************
delete SC; //i think that this line might cause an error
//******************************************************
return 0;
}
我想,我应该delete
让每个指针都释放堆内存?!你能指出我的错误吗?
编辑:
这是我的真实代码:
#include <iostream>
#include <string>
using namespace std;
class Pizza {
string dough;
public:
Pizza(string d):dough(d) {}
void setDough( string value ) { dough = value; }
string getDough() { return dough; }
};
class PizzaBuilder {
Pizza* pizza;
public:
PizzaBuilder( Pizza* p ) { pizza = p; }
~PizzaBuilder() { delete pizza; cout << "PizzaBuilder Destructor." << endl;}
PizzaBuilder* addExtra(string extra) {
string special = pizza->getDough() + " and extra " + extra;
pizza->setDough(special);
return this;
}
Pizza* getPizza() { return pizza; }
};
int main(int argc, char* argv[]) {
Pizza* p = new Pizza("My Special DOVE!");
PizzaBuilder* pb = new PizzaBuilder(p);
pb->addExtra("Mushrooms")->addExtra("Anchovies")->addExtra("Zefir")->addExtra("Chilli");
cout << p->getDough() << endl;
delete pb;
delete p;
return 0;
}