构造函数中的类错误
classes error at constructor
class name {
char *s;
int len;
public:
name(){ // Default constr.
s=NULL;
len =0;
}
//**************************************************
~name(){ // Destruct.
if (s!=NULL){
delete [] s;
s=NULL;
}
}
//*************************************************
name(const char * s1); // Constr.
char* getName(); //fcn get name
int getLen() ; // fcn get lenght
void setName(const char * s1); // fcn set name
};
void name::setName(const char * s1){
if (s!=NULL){
delete [] s;
s=NULL;
}
len = strlen(s1)+1;
s=new char [len]; // back***
strcpy(s,s1);
}
name::name(const char * s1){
if (s!=NULL){
delete [] s;
s=NULL;
}
len = strlen(s1)+1;
s=new char [len]; // back***
strcpy(s,s1);
}
char* name::getName(){
return s ;
}
int name::getLen(){
return strlen(s)+1 ;
}
int main()
{
char C[20];
cout << "Please enter a name: ";
cin >> C;
name AAA(C);
name BBB;
BBB.setName(C);
cout << "nThe length of A(" << AAA.getName();
cout << ") is: a" << AAA.getLen() << endl << endl;
cout << "nThe length of B(" << BBB.getName();
cout << ") is: a" << BBB.getLen() << endl << endl;
system("pause");
return 0;
}
当我运行代码时,类"BBB"成功执行,但"AAA"给了我运行时错误!
错误:
test0.exe: 0xC0000005: 访问冲突读取位置0xccccccc0 0x651157aa (msvcr100d.dll( 处未处理的异常。
在这里:
name::name(const char * s1){
if (s!=NULL){
是坏事发生的地方。 s
尚未初始化,您正在将其与NULL
进行比较。为什么你觉得它最初是NULL
的?这是未定义的行为。只需放弃条件 - 这是构建对象的地方,所以这样做 - 构建它。
强制性C++建议 - 使用std::string
。
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 模板,函数使用错误的构造函数来复制我的对象
- C++ OpenCV 卡尔曼滤波器构造函数错误
- 不命名构造函数和析构函数上的类型错误
- 处理简单 cpp 类构造函数中的错误
- 类和构造函数中的函数根本不起作用,并且不返回任何错误
- 链接器错误:无法解析构造函数
- 当我尝试通过构造函数分配 char 数组时出现错误
- 没有参数的构造函数给我错误
- 使用复制构造函数的程序输出错误
- 默认构造函数上的分段错误
- 错误: 无效使用非静态数据成员"应用程序::应用程序构造函数"
- 为什么定义复制构造函数会给我错误:无法将类型 'obj&' 的非常量左值引用绑定到类型为"obj"的右值?
- 带有 QWidget 的分段错误构造函数.Qt/C++
- C++错误构造函数参数
- 错误:构造函数未命名类型
- 错误:构造函数在此上下文中受到保护
- 没有匹配的函数错误C++构造函数
- 错误:构造函数的多个定义