1. 程式人生 > >C++各種構造函數使用的例子 beilinoj

C++各種構造函數使用的例子 beilinoj

作者 () del 例子 har using int() ons oid

#include<iostream>
#include<string.h>
using namespace std;

class Book
{
private:
char *name; //書名
char *author; //作者
int sale; //銷售量
public:
Book(); //無參構造函數
Book(char *a, char *b, int c); //有參構造函數
Book(const Book &x); //拷貝構造函數

void print(); //顯示數據
~Book(); //析構函數
};

Book::Book()
{
name=new char[10];
strcpy(name,"No name");
author=new char[10];
strcpy(author,"No author");
sale=0;
}
Book::Book(char *a,char *b,int c)
{
name=new char[strlen(a)+1];
strcpy(name,a);
author=new char[strlen(b)+1];

strcpy(author,b);
sale=c;
}
Book::Book(const Book &x)
{
name=new char[strlen(x.name)+1];
strcpy(name,x.name);
author=new char[strlen(x.author)+1];
strcpy(author,x.author);
sale=x.sale;
}
void Book::print()
{
cout<<name<<endl<<author<<endl<<sale<<endl;
}
Book::~Book()
{
delete []name;
delete []author;
}

int main()
{
char a[100];
char b[100];
int c;
gets(a);
gets(b);
cin>>c;
Book bk1(a,b,c);
Book bk2(bk1);
bk2.print();

return 0;
}

C++各種構造函數使用的例子 beilinoj