首页 > 编程语言 > 详细

c++类中系统默认拷贝构造函数的解析

时间:2014-03-27 00:24:43      阅读:634      评论:0      收藏:0      [点我收藏+]

我们在定义了一个c++类后, 如果我们自己没有写拷贝构造函数 , 那么系统就会系统一个默认的拷贝构造函数 , 但如果我们类中存在指针等地址变量时 , 就会发生意想不到的结构:

代码1、调用系统拷贝构造函数:

#include <iostream>
#include <stdio.h>
using namespace std;

class point
{
public:
    point()  {}
    point(string *c)  { z = c;}
    void set2();
    string get();

private:
    string *z;

};


string point::get()
{
    return z[0];
}
void point::set2()
{
    z[0] = "xy";
} 

int main()
{
    string xy[3] = {"wef" , "efe" , "wre"};
    point a(xy);
    point b(a);
    a.set2();
    cout << a.get() << endl;
    cout << b.get() << endl;
    return 0;
}
输出的结果是:

bubuko.com,布布扣


代码2、调用自定义的拷贝构造函数:#include <iostream>

#include <iostream>
#include <stdio.h>
using namespace std;

class point
{
public:
    point()  {}
    point(const point &c , int new_size);
    point(string *c)  {z = c;}
    void set2();
    string get();

private:
    string *z;

};


string point::get()
{
    return z[0];
}
void point::set2()
{
    z[0] = "xy";
}
point::point(const point &c , int new_size)
{
    z = new string[new_size];
    for(int i = 0; i < new_size; i++)
        z[i] = c.z[i];
}
int main()
{
    string xy[3] = {"wef" , "efe" , "wre"};
    point a(xy);
    point b(a , 3);
    a.set2();
    cout << a.get() << endl;
    cout << b.get() << endl;
    return 0;
}
输出结果是:

bubuko.com,布布扣

c++类中系统默认拷贝构造函数的解析,布布扣,bubuko.com

c++类中系统默认拷贝构造函数的解析

原文:http://blog.csdn.net/zengchen__acmer/article/details/22213335

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!