您的位置:首页 > 编程语言 > C语言/C++

c++指针悬挂

2012-10-09 19:56 190 查看
在C++中对于任何一个类,如果没有用户自定义的赋值运算符函数,系统会自动地为其生成默认的赋值运算函数,以完成数据成员之间的逐位复制。通常情况下,系统默认的赋值函数可以完成赋值任务,但在某些特殊情况下,如类中有指针类形式,就不能进行直接相互赋值,否则就会产生指针悬挂问题!

例如:

class Student

{

private:

  char *name;

  int score;

public:

  Student(char *na,int s);

  ~Student();

  void print();

};

#include"iostream"

#include"iomanip"

using namespace std;

#include"student.h"

int main()

{

  Student p1("zhang",90);

  Student p2("wang",80);

  p2 = p1;

  cout<<"p2:";

  p2.print();

  return 0;

}

Student::Student(char *na,int s)

{

  name = new char[strlen(na) + 1];

  strcpy(name,na);

  score = s;

}

Student::~Student()

{

  delete name;

}

void Student::print()

{

  cout<<name<<setw(5)<<score<<endl;

}

程序将显示运行结果出错的信息

原因:



p2生命周期结束后,p1的指针所指的空间就不存在了,产生指针悬挂

解决的方法是:重载赋值运算符解决指针悬挂问题

class Student
{
private:
char *name;
int score;
public:
Student(char *na,int s);
Student &operator =(const Student &);
~Student();
void print();
};

#include"iomanip"
#include"iostream"
using namespace std;
#include"string.h"
#include"student.h"

int main()
{
Student p1("zhang",90);
Student p2("wang",80);
cout<<" p2: ";
p2.print();
p2 = p1;
cout<<"修改后p2: ";
p2.print();
return 0;
}

Student::Student(char *na, int s)
{
name = new char[strlen(na) + 1];
strcpy(name,na);
score = s;
}

Student &Student::operator =(const Student &p) //定义赋值运算符重载
{
if(this == &p)
return *this;
delete name; //释放掉原空间
name = new char[strlen(p.name) + 1]; //分配新空间
strcpy(name,p.name);
return *this;
}

Student::~Student()
{
delete name;
}

void Student::print()
{
cout<<name<<setw(5)<<score<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: