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

C++各种构造函数使用的例子

时间:2019-03-24 09:31:17      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:space   销售   book   ret   end   pac   mes   auth   name   

#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++各种构造函数使用的例子

标签:space   销售   book   ret   end   pac   mes   auth   name   

原文地址:https://www.cnblogs.com/Cecilia-Jr/p/10586832.html

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