标签:
初学者学习构造函数和析构函数,面对如何构造的问题,会头大。这里提供了变量(int,double,string),char *,字符数组三个类型的私有成员初始化的方法
//char * 类型的成员,如何在构造函数中初始化(弄了一个晚上才搞定); //析构函数中记得用delete指令取消内存分配; //string,int,double...都是直接赋值; //public 可以改变 私有成员的值 ! #include"std_lib_facilities.h" class book{ public: book(string n, char ch[],char *dd){ name = n; strcpy_s(isbn,12, ch); kk = new char[strlen(dd) + 1]; //Constructor:learn the way to do it! strcpy_s(kk, strlen(dd) + 1, dd); } void printbook(); // printbook(book b) .exe stop! virtual ~book(); private: string name; char isbn[11]; char * kk; }; book::~book(){ delete [] kk; // Destructor:get the memry back; } void book::printbook() { cout << name << endl<<isbn <<endl<<kk << endl; } int main(){ book a("hanxinle","12345678901","asdf"); a.printbook(); return 0; }
标签:
原文地址:http://www.cnblogs.com/hanxinle/p/4839552.html