初学C++,有点类数组定义的问题不太明白
以下是我刚看完类与对象这章写的小程序,发现以下注释掉的类初始化会导致析构函数double free or corruption (fasttop): 0x08c80038 *** ,编译环境linux g++。VC能运行,但是name打印出乱码,用没有注释掉的定义方式是可行的。我刚看c++几天,问的太弱希望别见怪。。。
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
int age;
char *name;
public:
Student(int,char *);
Student();
~Student();
void SetName(int,char *);
int Getage(){return age;}
char *GetName(){return name;}
};
Student::Student(int m,char *n)
{
cout<<"Paramater!"<<endl;
age=m;
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::Student()
{
cout<<"No paramater!"<<endl;
age=0;
char *n="baolun";
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::~Student()
{
cout<<"Free student!"<<endl;
delete []name;
}
void Student::SetName(int m ,char *n)
{
age=m;
name=new char(strlen(n)+1);
strcpy(name,n);
}
main()
{
int i;
/* Student stu[3];
stu[0]=Student();
stu[1]=Student(21,"yanhufen");
stu[2]=Student(19,"baocaomin");*/
Student stu[3]=
{
Student(),
Student(31,"sldjfl"),
Student(19,"baocaomin")
};
for(i=0;i<3;i++)
{
cout<<"Stu["<<i<<"]: ";
cout<<"Name:"<<stu[i].GetName()<<" ";
cout<<"Age:"<<stu[i].Getage()<<endl;
}
}
#include<iostream>
#include<string.h>
using namespace std;
class Student
{
int age;
char *name;
public:
Student(int,char *);
Student();
~Student();
void SetName(int,char *);
int Getage(){return age;}
char *GetName(){return name;}
};
Student::Student(int m,char *n)
{
cout<<"Paramater!"<<endl;
age=m;
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::Student()
{
cout<<"No paramater!"<<endl;
age=0;
char *n="baolun";
name=new char[strlen(n)+1];
strcpy(name,n);
}
Student::~Student()
{
cout<<"Free student!"<<endl;
delete []name;
}
void Student::SetName(int m ,char *n)
{
age=m;
name=new char(strlen(n)+1);
strcpy(name,n);
}
main()
{
int i;
/* Student stu[3];
stu[0]=Student();
stu[1]=Student(21,"yanhufen");
stu[2]=Student(19,"baocaomin");*/
Student stu[3]=
{
Student(),
Student(31,"sldjfl"),
Student(19,"baocaomin")
};
for(i=0;i<3;i++)
{
cout<<"Stu["<<i<<"]: ";
cout<<"Name:"<<stu[i].GetName()<<" ";
cout<<"Age:"<<stu[i].Getage()<<endl;
}
}
...全文
相关推荐
让所有初学者都明白java程序结构
总结来说,理解Java程序结构对于初学者至关重要,它包括导入必要的类库(`import`)、定义类及其继承关系(`class define`)、声明类的数据成员(`field`)、添加注释以提高可读性(
C语言初学者相关代码
当遇到错误或不明白的地方时,尝试查找资料、阅读相关的C语言书籍或在线教程,以加深理解。记住,编程是一项实践性极强的技能,只有通过不断的练习和实际编程,才能真正掌握C语言。
初学者要明白,编程的基础真的很重要.docx
例如,使用现成的控件而不理解其工作原理,可能会导致在遇到特定问题时束手无策。学习编程应该遵循一定的顺序,通常推荐先从C/C++这样的低级语言开始,因为它们更接近底层,有助于理解计算机工作原理。
C++/C 实例 初学者有帮助
由于这些实例可能沿用了C语言的语法,初学者也需要了解C语言的一些特性,如:1. **C语言的基本语法**:与C++相似,但不包含面向对象特性。2. **预处理器**:如#include指令,宏定义等。
明明白白C指针.pdf
### 结论通过以上分析可以看出,《明明白白C指针.pdf》这份文档通过具体的示例和对比,系统地介绍了C语言中指针的基本概念及其用法。对于初学者而言,理解这些基础知识是非常重要的。


