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
};
- 写一个类,书写三个函数. 默认构造函数,virtual函数,拷贝构造函数.
- 如果真的不希望拷贝构造函数,声明为private.