在继承时如何正确编写复制构造函数,析构函数和赋值运算符?

时间:2013-05-01 21:35:58

标签: c++

这是对的吗?

class SearchString : public NString {

  DataForSearchInString dataForSearchInString;

public:
    SearchString():NString(){}
    SearchString(const char * data):NString(data){}
    SearchString(const SearchString & other) : NString(other), dataForSearchInString() {}

    SearchString& operator=(const SearchString& other)
    {
        NString::operator=(other);
        dataForSearchInString.setBegin(other.getBegin());
        return *this;
    }

    // if will be classes - children or there any virtual function then need to write "virtual ~SearchString() {}"  here 

    //  Some functions 
    inline const int getBegin() const {return dataForSearchInString.getBegin();} 
};

1 个答案:

答案 0 :(得分:0)

似乎没问题,但我想你忘了DataForSearchInString(other.dataForSearchInString)

class SearchString : public NString {

    DataForSearchInString dataForSearchInString;

public:
    SearchString():NString(){}
    SearchString(const char * data):NString(data){}
    SearchString(const SearchString & other) : 
                            NString(other),
                            DataForSearchInString(other.dataForSearchInString) {}
                                                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    SearchString& operator=(const SearchString& other)
    {
        NString::operator=(other);
        dataForSearchInString.setBegin(other.getBegin());
        return *this;
    }
};