常資料成員的深複製,const+字元型指標 ,如何寫深複製的程式碼?

程式碼女民工發表於2021-09-24

#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部落格 ” ,連結:http://blog.itpub.net/70007056/viewspace-2793569/,如需轉載,請註明出處,否則將追究法律責任。

相關文章