#指针与复制构造函数
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
using std::cout;
using std::endl;
struct Node
{
char *name;
int age;
Node(char *n=" ",int a=0)
{
name = strdup(n);//strdup()在内部调用了malloc()为变量分配内存,不需要使用返回的字符串时,
//需要用free()释放相应的内存空间,否则会造成内存泄漏。
age = a;
}
Node(const Node & n)//copy constructor
{
name = strdup(n.name); //Allocate memory internally
age = n.age;
}
// Node & operator=(const Node & n)
// {
// if(this!=&n)
// {
// if(name!=0) free(name);
// name = strdup(n.name);
// age = n.age;
// }
// return *this;//*this is the object itself
// }
~Node()
{
if(name!=0)free(name);//As for a char character, number 0 standard for \0;
}
};
int main()
{
cout << "Hello world ! For a long time!" << endl;
Node node1("A",10), node2(node1), node3 = node1;//<=======call default copy constructor
strcpy(node1.name, "B");
node1.age=20;
cout << "have copy constructor but no operator =:\n" << "node1.name:" << node1.name << "\tnode2.name:" << node2.name << "\tnode3.name:" << node3.name << endl;
cout << "node1.age:" << node1.age << "\tnode2.age:" << node2.age << "\tnode3.age:" << node3.age << endl;
// No copy constructor but operator =:
// node1.name:B node2.name:B node3.name:B
// node1.age:20 node2.age:10 node3.age:10
// have copy constructor but no operator =: <====It seems that operator = have no influence........
// node1.name:B node2.name:A node3.name:A
// node1.age:20 node2.age:10 node3.age:10
// 编译器的默认复制构造函数只是逐个复制,node2.name指针没有指向重新分配内存空间,而是直接将node1.name指针指向的地址复制过去,
// 两个指针指向同一内存!!!因此存在指针的情况必须定义复制构造函数
return 0;
}