//拷貝建構函式呼叫的三種情況
//1.用一個類去初始化另一個類 A a; A b(a);
//2.類物件作爲函數參數傳遞,void fun(A a);
//3.函數的返回值爲類物件 A fun(){A a;return a;}
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
char* mystrcpy(char *dest,const char*src){
if (src == NULL)
{
return NULL;
}
if (dest == NULL)
{
return NULL;
}
char *p = dest;
while (*src != '\0')
{
*p = *src;
p++;
src++;
if (*p == '\0')
{
break;
}
}
*p = '\0';
return dest;
}
class A
{
void* m_pData;
int m_nSize;
public:
A(){
m_pData = NULL;
m_nSize = 0;
}
A(int sz){
if (sz > 0)
{
m_nSize = sz;
m_pData = (void*)(new char[m_nSize]);
}
}
//拷貝建構函式呼叫的三種情況
//1.用一個類去初始化另一個類 A a; A b(a);
//2.類物件作爲函數參數傳遞,void fun(A a);
//3.函數的返回值爲類物件 A fun(){A a;return a;}
A(const A &a){
cout<<"拷貝建構函式呼叫\n";
m_nSize = a.m_nSize;
if(m_nSize>0){
m_pData = (void*)(new char[m_nSize]);
}
}
A& operator =(const A &a){
cout<<"賦值呼叫\n";
A a1;
a1.m_nSize = a.m_nSize;
if(a1.m_nSize>0){
a1.m_pData = (void*)(new char[m_nSize]);
}
return a1;
}
};
//2
void fun(A a){
}
//3
A func(){
A a;
return a;
}
int main(){
A a;
A b(a);//1
fun(a);
A c = func();
//賦值運算
c = b;
while(1);
return 0;
}
輸出:
拷貝建構函式呼叫
拷貝建構函式呼叫
拷貝建構函式呼叫
賦值呼叫