码迷,mamicode.com
首页 > 编程语言 > 详细

节省创建对象数组的技巧

时间:2015-01-07 10:49:25      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

...
不管
Student obj[10];//obj是指针首地址
还是
Student* pStudent=new Student[10];
...
delete  pStudent; ...
实际上最终给各个对象初始化的时候调用的都是默认的构造函数(结构体是没有构造函数的),如果有重载的构造函数的话,再使用这种方式岂不浪费时间?以下是解决方法:
class Student
{
public:
     Student();
     Student(char name[20],int age,float score);
     ~Student();
     void setName(char name[20]){strcpy(this->name,name);}//内联,this指的是当前对象的首地址
     void setAge(int age){this->age=age;}//这也是一种内联函数
     void setScore(float score){this->score=score;}//这也是一种内联函数
     char* getName(){return name;}//这也是一种内联函数
     int getAge(){return age;}
     float getScore(){return score;}
private:
     char name[20];
     int age;
     float score;
};

Student::Student()
{
     cout<<"Stduent constructor"<<endl;
}
Student::Student(char name[20],int age,float score)
{
     cout<<"Stduent constructor"<<endl;
     strcpy(this->name,name);
     this->age=age;
     this->score=score;
}
Student::~Student()
{
     cout<<"Stduent destroy"<<endl;
}

void fun44()
{
     typedef Student* pStu;
     Student** ppStu;
     ppStu= new pStu[10];
     //ppStu[0]->age=20; //错误的写法,因为ppStu[0]仅仅是一个指针,但没有指向任何Student对象
     for (int i=0;i<10;i++)
     {
          *(ppStu+i)=new Student("ccc",i,i/2.0f);//此处调用了重载的构造函数,把new出来的首地址传给*(pStu+i)
     }
     //先释放掉指针数组里的每一个指针,再释放指针数组
     for (int i=0;i<10;i++)
     {
          delete ppStu[i];
     }
     delete [] ppStu;
}
================
1.C++里的内联函数实际上是可以不加inline ,直接把实现定义在class里即可,但要注意代码要短小,Java和C#的编译器实际上也有类似的处理机制,只不过对程序员是透明的
2. 巧妙的运用多星指针,先开辟指向Student的指针(这时的指针都是空指针,不能用),再一个个的new
3. 多星指针的释放,指针的释放确实麻烦,.NET和Java去掉指针也不无道理,但这是以牺牲性能为代价的

节省创建对象数组的技巧

标签:

原文地址:http://www.cnblogs.com/QQ122252656/p/4207751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!