注册 登录
编程论坛 C++教室

复制构造函数

大剑 发布于 2012-02-15 13:27, 691 次点击
复制构造函数在那?
程序代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
class CStudent
{
private:
    char *p_name;
    int age;
public:
    CStudent(char *,int);
    ~CStudent() {
        if(p_name!=NULL)
            delete p_name;
        cout<<"destructor of class"<<endl;
    }
    void show(void);
};
CStudent::CStudent(char *source,int a)
{
    p_name=new(char[strlen(source)+1]);
    strcpy(p_name,source);
    age=a;
}
void CStudent::show()
{
    cout<<p_name<<" "<<age<<endl;
}
void main()
{
    CStudent *p_student=new CStudent("张三",20);
    CStudent stud1("李四",50);
    CStudent stud3(stud1);

    p_student->show();
    stud1.show();
    stud3.show();
    delete p_student;
}


出现这个状况 那位帅哥帮忙解释下。
只有本站会员才能查看附件,请 登录

3 回复
#2
rjsp2012-02-15 14:29
程序代码:
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>

class CStudent
{
    friend std::ostream& operator<<( std::ostream&, const CStudent& );
public:
    CStudent( const char* name, unsigned int age );
    CStudent( const CStudent& rhs );
    CStudent& operator=( const CStudent& rhs );
    ~CStudent();
    void show(void);
private:
    char* name_;
    unsigned int age_;

};

using namespace std;

CStudent::CStudent( const char* name, unsigned int age )
{
    name_ = new char[strlen(name)+1];
    strcpy( name_, name );
    age_ = age;
}
CStudent::CStudent( const CStudent& rhs )
{
    name_ = new char[strlen(rhs.name_)+1];
    strcpy( name_, rhs.name_ );
    age_ = rhs.age_;
}
CStudent& CStudent::operator=( const CStudent& rhs )
{
    if( this != &rhs )
    {
        delete[] name_;

        name_ = new char[strlen(rhs.name_)+1];
        strcpy( name_, rhs.name_ );
        age_ = rhs.age_;
    }
    return *this;
}
CStudent::~CStudent()
{
    delete[] name_;
    cout<<"destructor of class"<<endl;
}
ostream& operator<<( ostream& os, const CStudent& st )
{
    return os << st.name_ << ' ' << st.age_;
}

int main()
{
    CStudent* pst1 = new CStudent("张三",20);
    CStudent st2("李四",50);
    CStudent st3(st2);

    cout << *pst1 << endl;
    cout << st2 << endl;
    cout << st3 << endl;

    delete pst1;
    return 0;
}
#3
我菜1192012-02-18 21:10
所谓的复制构造其实就是拷贝构造函数,只是叫法不一样。
构造函数分为浅拷贝和深拷贝,深拷贝构造函数就是拷贝构造函数,一般来说我们不必自己写浅拷贝构造函数,因为系统会调用“=”运算符重载函数,但是如果一个类中含有指针变量的话,就要自己写拷贝构造函数了,因为涉及到类对象销毁后内存的问题!

看了你的另一篇帖子,你还是把C++的基础知识好好的掌握一下,基本太弱了!
#4
lz10919149992012-02-18 22:46
1