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

关于派生类的复制构造函数问题,实在想不通

骇客不会飞 发布于 2013-10-02 13:03, 523 次点击
class AAA
{
    private:
         char * label;
         int rating;
    public:
         AAA(const AAA &rs);
        …………
}
AAA::AAA(const AAA & rs)
{
label=new char[strlen(rs.label)+1];
strcpy(label,rs.label);
rating=rs.rating;
}

class BBB:public AAA
{
   private:
         char * color[10];
   public:
   friend std::ostream & operator<<(std::ostream & os,const BBB & rs);  //输出为BBB派生类的三个数据成员,定义懒得写;
  …………   //无派生类的构造函数
}
int main()
{
BBB balloon("red","blimpo",4);     //其中也包含了对AAA基类的数据成员初始化
BBB ballon2(balloon);
cout<<balloon2<<endl;
}
输出结果为balloon的三个值(即red ,blimpo ,4),书上说的是如果没有为派生类显式定义复制构造函数,那么派生类默认使用基类的复制构造函数复制基类的部分,我的问题:按照说法应该是:复制构造函数只复制了label和rating的值,怎么连color值也复制给了balloon2呢?
3 回复
#2
blueskiner2013-10-02 16:04
你应该在BBB的构造里处理AAA的构造。
#3
blueskiner2013-10-02 16:21
刚想了想,你的代码很多问题,我给你打了一份,有些需要加分号之类的细节不能忽视。请养成严谨的风格。

#include <iostream>


class AAA
{
private:
    char* label;
    int rating;
public:
    AAA(const AAA& rs)
    {
        label=new char[strlen(rs.label)+1];
        strcpy(label,rs.label);
        rating=rs.rating;
    }
    AAA(const char* pC, int nR)
    {
        label=new char[strlen(pC)+1];
        strcpy(label,pC);
        rating=nR;
    }
};

class BBB : public AAA
{
private:
    char color[10];
public:
    friend std::ostream & operator<<(std::ostream & os,const BBB & rs) {  //输出为BBB派生类的三个数据成员,定义懒得写;
        std::cout << "Label" << std::endl;
        std::cout << "Rating" << std::endl;
        std::cout << "Color" << std::endl;
        return os;
    }

    //无派生类的构造函数
    BBB(const AAA& a, const char* pC) : AAA(a)
    {
        strcpy(color, pC);
    }
};

int main(int argc, char** argv)
{
    AAA av("blimpo", 4);
    BBB balloon(av, "red");   //其中也包含了对AAA基类的数据成员初始化
    BBB ballon2(balloon);
    std::cout<<ballon2<<std::endl;

    return 0;
}
#4
骇客不会飞2013-10-02 20:58
回复 3楼 blueskiner
其实那些我都懒得写出来而已
1