![]() |
#2
a8612684482015-04-13 19:37
|

#include<iostream>
#include<cstring>
using namespace std;
class computer
{
private:
char *brand;
float price;
public:
computer(const char *sz,float p){
brand=new char [strlen(sz)+1];
strcpy(brand,sz);
price=p;}
~computer()
{ delete[] brand;
cout<<"清理"<<endl;
}
void print(){
cout<<"品牌"<<brand<<endl;
cout<<"价格"<<price<<endl;
}
};
#include<cstring>
using namespace std;
class computer
{
private:
char *brand;
float price;
public:
computer(const char *sz,float p){
brand=new char [strlen(sz)+1];
strcpy(brand,sz);
price=p;}
~computer()
{ delete[] brand;
cout<<"清理"<<endl;
}
void print(){
cout<<"品牌"<<brand<<endl;
cout<<"价格"<<price<<endl;
}
};
这个是源程序

#include"example.h"
int main()
{
computer comp("dell",7000);
comp.print();
return 0;
}
int main()
{
computer comp("dell",7000);
comp.print();
return 0;
}
我的困惑是在example.h中不是首先new brand,然后就是析构函数里面的delete吗?
为什么接下来的输出brand会没有问题呢?我感觉输出是brand不是野指针吗?