首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

一段c++代码,编译,组装都没有错,运行不了,为啥,求指教!

2013-01-05 
一段c++代码,编译,组建都没有错,运行不了,为啥,求指教!!一段c++代码,编译,组建都没有错,运行不了,为啥,求

一段c++代码,编译,组建都没有错,运行不了,为啥,求指教!!
一段c++代码,编译,组建都没有错,运行不了,为啥,求指教!!
//.........................................
//test.cpp
//.........................................
#include<iostream>
using namespace std;
//.........................................
class person{

int hight,weight;
char* pName;
public:
person(char* pn="NOname",int x=0,int y=0){

pName = pn;
hight = x;
weight = y;
}

person(const person& s){


cout<<"copy constructing "<<s.pName<<"\n";
pName = new char(strlen(s.pName)+1);
pName = s.pName;
hight = s.hight;
weight = s.weight;
}

~person(){

cout<<"Destructing "<<pName<<"\n";
delete[] pName;
}

};//........................................

void  main(){

person p1("Randy",90,90);
person p2(p1);

}//================================================



[解决办法]
帮你调了一下,原因就不解释了
//.........................................
 //test.cpp
 //.........................................
 #include<iostream>
 using namespace std;
 //.........................................
 class person{

 int hight,weight;
 char* pName;
 public:
 person(char* pn="NOname",int x=0,int y=0){

 pName = pn;
 hight = x;
 weight = y;
 }
 
person(const person& s){


 cout<<"copy constructing "<<s.pName<<"\n";
 //pName = new char[strlen(s.pName)+1];
 pName = s.pName;
 hight = s.hight;
 weight = s.weight;
 }

 ~person(){

 cout<<"Destructing "<<pName<<"\n";
 //delete []pName;
 }
 
};//........................................
 
void  main(){
 
person p1("Randy",90,90);
 person p2(p1);
 
}//================================================
[解决办法]
建议你先把指针的概念理解清楚,还有看看林锐的高质量C++编程

pName = new char(strlen(s.pName)+1);这个很有问题
且,你的构造函数不应该这么写,如果是一个局部变量,那么会导致内存访问问题
[解决办法]
person(const person& s){

 cout<<"copy constructing "<<s.pName<<"\n";
 //pName = new char[strlen(s.pName)+1];
 pName = s.pName;  //以盲導盲
 hight = s.hight;
 weight = s.weight;
 }
[解决办法]

#include<iostream>
#include <string>
using namespace std;
//.........................................
class person{

int hight,weight;
string pName;                //用string類型
public:
person(string pn="NOname",int x=0,int y=0){

pName = pn;
hight = x;
weight = y;
}



person(const person& s){
cout<<"copy constructing "<<s.pName<<"\n";
//pName = new char(strlen(s.pName)+1);
pName = s.pName;
hight = s.hight;
weight = s.weight;
}

~person(){

//cout<<"Destructing "<<pName<<"\n";
//delete[] pName;
}

};//........................................

int  main(){

person p1("Randy",90,90);
person p2(p1);
return 0;
}//==================

热点排行