code of C/C++(2)

时间:2022-10-14 18:52:07

初学者学习构造函数和析构函数,面对如何构造的问题,会头大。这里提供了变量(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,, ch);
kk = new char[strlen(dd) + ]; //Constructor:learn the way to do it!
strcpy_s(kk, strlen(dd) + , dd);
}
void printbook(); // printbook(book b) .exe stop!
virtual ~book();
private:
string name;
char isbn[];
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","","asdf");
a.printbook(); return ;
}