C++类的例子

cat person.cpp
#include <iostream>
#include <cstring>
using namespace std;

class Person {
public:
 //无参构造函数
 Person();
 // 有参构造函数
 Person(int myage, const char *myname);
 //析构函数
 ~Person();
 //拷贝构造函数
 Person(const Person& b);
 //赋值函数
 Person& operator=(const Person& b);
 //普通成员函数
 void display();
private:
  int age;
  char *name;
};

Person::Person()
:age(10),name(NULL)
{
 cout << "Person::Person() 无参构造函数被调用 " << endl;
 //age = 10;
 name = new char[20];
 strcpy(name, "XiaoMing");
}
Person::Person(int age, const char *name)
{
 cout << "Person::Person(int, const char*) 有参构造函数被调用 " << endl;
 this->age = age;
 this->name = new char[strlen(name)+1];
 strcpy(this->name, name);
}
#if 1
/**
 * 等号运算符重载
 */
Person& Person::operator=(const Person& b)
{
    cout<<"Person::operator() 赋值函数被调用 "<<endl;
 if(this == &b)
  return *this;

 this->age = b.age;
 delete[] name;
 this->name = new char[strlen(b.name)+1];
 strcpy(this->name, b.name);

 return *this;
}
#endif

Person::Person(const Person& b)
{
 cout << "Person::Person(const Person&) 拷贝函数被调用" << endl;
 this->age = b.age;
 //delete[] name;//这个是构造函数在初始化,这之前对象还未存在
 this->name = new char[strlen(b.name)+1];
 strcpy(this->name, b.name);

 //return *this;//构造函数没有返回值
}
Person::~Person(void)
{
 cout << "Person::~Person() 虚构函数被调用 " << endl;
 delete[] name;
}
void Person::display()
{
 cout << "数据显示:Name:" << name << ", Age:" << age << endl;
 return;
}

int main()
{
#if 0
 Person a; //Person::Person()
 a.display();
#endif
#if 0
 Person b(20, "XiaoLi"); //Person::Person(int, char*)
 b.display();
#endif
#if 0
    // 调用等号运算符重载函数
 a = b;//赋值 调用了operator=(...)赋值函数
 a.display();
#endif

#if 0
 cout << "=====" << endl;
 Person c = b; //不是赋值,是初始化,调用了拷贝构造函数,而不是赋值函数
 c.display();

 //Person d = d; //这种不可能,因为d还不存在
#endif

#if 0
    /* 调用参构造 */
 Person *pa = new Person;
 pa->display();
 delete pa;
#endif

#if 0
 Person *pb = new Person(20, "XiaoLi");
 pb->display();
 delete pb;
#endif

 return 0;
}

原文链接: https://www.cnblogs.com/langqi250/archive/2012/11/13/2767874.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++类的例子

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/69201

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午1:41
下一篇 2023年2月9日 下午1:42

相关推荐