27.拷贝构造-II

class Person
{
public:
Person(const char *s);
~Person();
void print();
private:
char *name;
};
//没有写自己的拷贝构造函数
//编译器自己给的拷贝构造,新的对象指针和老的对象指针是相同的.

#ifndef _PERSON_H
#define _PERSON_H
class Person
{
  public:
    Person(const char *s);
    ~Person();
    void print();
    char *name;
};
#include "Person.h"
#include <cstring>
using namespace std;

Person::Person(const char *s)
{
  name = new char[::strlen(s)+1];
  ::strcpy(name,s);
}

Person::~Person()
{
   delete [] name;
}
#include <stdio.h>
#include "person.h"

int main()
{
   Person p1("John"); 
   Person p2(p1);
   printf("p1.name = %p\n",p1.name); //p1.name = 0001;
   printf("p2.name = %p\n",p2.name); //p2.name = 0001;
   //p1,p2指向同一段字符串的内存,p1析构了一遍, p2又析构了一遍,释放两次,代码出错.
   return 0;
}

调用拷贝构造函数
1. 调用函数,参数是一个对象本身,而不是引用或指针.
2. Person baby_b = baby_a;
Person baby_c(baby_a);
3. 函数返回一个对象

#include <stdio.h>
#include "person.h"
Person f()
{
   Person ip; //默认构造
   return ip;
}

int main()
{
   Person p = f(); //编译器可能把不必要的构造优化掉
   return 0;
}
Person copy_func(char *who)
{
   person local(who);
   local.print();
   return local; // copy ctor called!
}

Person nocopy_func(char *who)
{
   return Person(who);
} // no copy needed! 大部分编译器优化掉了

任何对象初始化一次,其它是赋值.

用string类做事情, 不建议用char*
用char* 是我要访问内存了, 用二进制的东西byte

#include <string>
class Person
{
  public:
    Person(const string&);
    ~Person();
    void print();
    // ... other accessor fxns
  private:
    string name;
    // ... other data members
};
  1. 写一个类,书写三个函数. 默认构造函数,virtual函数,拷贝构造函数.
  2. 如果真的不希望拷贝构造函数,声明为private.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值