ITPub博客

首页 > 应用开发 > C/C++ > 常数据成员的深拷贝,const+字符型指针 ,如何写深拷贝的代码?

常数据成员的深拷贝,const+字符型指针 ,如何写深拷贝的代码?

原创 C/C++ 作者:代码女民工 时间:2021-09-24 16:39:18 0 删除 编辑

#include <iostream>

#include <cstring>


class Student

{

public:

    Student( int no, const char* name, float score ) : no_(no), name_(strcpy(new char[strlen(name)+1],name)), score_(score)

    {

    }

    Student( const Student& s ) : no_(s.no_), name_(strcpy(new char[strlen(s.name_)+1],s.name_)), score_(s.score_)

    {

    }

    ~Student()

    {

        delete[] name_;

    }


protected:

    Student& operator=( const Student& s );


private:

    const int no_;

    const char* name_;

    const float score_;


    friend std::ostream& operator<<( std::ostream& os, const Student& s )

    {

        return os << s.no_ << ' ' << s.name_ << ' ' << s.score_;

    }

};


using namespace std;


int main( void )

{

    Student stu1( 1, "wangming", 99 );

    Student stu2 = stu1;

    cout << stu1 << '\n';

    cout << stu2 << '\n';

}


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70007056/viewspace-2793569/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2021-09-17

  • 博文量
    38
  • 访问量
    25129