我有一個簡單的類叫object
,我遇到了問題。 Theres一個方法,如果我叫它會導致段錯誤。我不明白爲什麼。C++類指針刪除segfaulting
typedef class object
{
private:
short id;
std::string name;
SDL_Rect offset;
public:
object();
object(short i, std::string n);
~object();
object(const object &o);
object& operator = (const object &o);
std::string get_name();
void set_name(std::string n);
} object;
object::object()
{
id = 0;
name = "";
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}
object::object(short i, std::string n)
{
id = i;
name = n;
offset.x = 0;
offset.y = 0;
offset.w = 0;
offset.h = 0;
}
object::~object()
{
delete &offset;
delete &id;
delete &name;
}
object& object::operator=(const object &o)
{
if(this != &o)
{
delete &name;
name.assign(o.name);
delete &id;
id = o.id;
delete &offset;
offset = o.offset;
}
return *this;
}
object::object(const object &o)
{
id = o.id;
name = o.name;
offset = o.offset;
}
// Functions
std::string object::get_name()
{
return name;
}
void object::set_name(std::string n)
{
name = n;
}
而且我的main.cpp
int main(int argc, char** argv)
{
struct object *a = new object(0, "test");
struct object *b = new object(1, "another test");
printf(a->get_name().c_str());
printf("\n");
printf(b->get_name().c_str());
b = a;
printf("\n");
printf(b->get_name().c_str());
a->set_name("Another test");
printf("\n");
printf(a->get_name().c_str());
delete a;
printf("\nDeleted a");
delete b;
printf("\nDeleted b");
return 0;
}
如果我打電話a->set_name("Another test");
,我得到一個段錯誤。如果我不打電話,沒有問題,一切正常。我可能錯過了一些簡單的東西,但我找不到它。它在賦值時不會出現段錯誤,但是如果該行在那裏,則在刪除指針時會崩潰。
你有[一個很好的C++的書(http://stackoverflow.com/questions/388242/the-definitive-c++-book-guide-and-list) ?如果沒有,我強烈建議您購買一個。 – 2010-10-25 16:19:22
是的..讓自己一本C++書.. :) – baash05 2010-10-26 00:36:58