本文介绍了[解决]如何在C ++中将堆栈声明转换为堆声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以帮助将以下堆栈声明转换为堆声明

Can anyone plz help to convert the following stack declarations to heap declarations

class student
{
   protected:
   int r;
   char sta,m;
   char student_roll[15];
   char name[50];
   char sex[10];
   char status[50];
   float slc,p2,m1,m2,m3,m4,m5,m6,m7,m8;
   float tp,p1,rem,pa;
   char dob[20];
   public:
   char roll_no[15];
};





请帮助....它是一个C ++类...



Please help....its a C++ class...

推荐答案

class student
{
  enum SEX {
    Female = 0,
    Male
  };
 
   protected:
   int r;
   char sta,m;
   std::string student_roll;
   std::string name;
   SEX sex;
   std::string status;
   float slc,p2,m1,m2,m3,m4,m5,m6,m7,m8;
   float tp,p1,rem,pa;
   std::string dob;
   public:
   std::string roll_no;
};


{
student s; // allocated on stack 
}






but

student* pStud = new student; // allocated on heap



但也许你想知道如何描述一个总是只能在堆上分配的类......请使用命名构造函数成语。

见这里:



这是你的类的新版本(如果你想在堆上只为> 对象分配一个内存):


But perhaps you're wondering how to describe a class that can always be allocated ONLY on heap... Please use the "Named Constructor Idiom".
See here : http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Named_Constructor

Here new version of your class (if you want allocate a memory for object of class only on heap):

class student
{
public:
    // The create() methods are the "named constructors":
   static student* create() { return new student(); }

protected:
   int r;
   char sta,m;
   char student_roll[15];
   char name[50];
   char sex[10];
   char status[50];
   float slc,p2,m1,m2,m3,m4,m5,m6,m7,m8;
   float tp,p1,rem,pa;
   char dob[20];
   public:
   char roll_no[15];

private:
   // The constructor IS private !!!!
  student();
};




 //Now exist only one way to create a student objects => a student::create() 
int main()
{
   student* p = student::create();
   ...
   delete p;
   ...
} 



这篇关于[解决]如何在C ++中将堆栈声明转换为堆声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 18:38