复制基类和派生类的构造函数

时间:2010-10-03 08:47:07

标签: c++

我有这两个班级

///////////BASE CLASS

    class Base{
    public:
     Base(int = 0);
     ~Base();
     Base(Base&);
     Base(Derived&);   ////<-may be problem here?, note: I tried without this function
     int valueOfBase();
    protected:
     int protectedData;
    private:
     int baseData;
    };

    /////////////DERIVED CLASS
    class Derived: public Base{
    public:
     Derived(int);
     //Derived(Derived&);
     ~Derived();
    private:
     int derivedData;
    };

and here my main

    int main(){
     Base base(1);
     Derived derived = base;
    return 0;
    }

我读过如果我的派生类没有复制c'tor copy c'tor of the base will be called,但每次收到conversion from Base to non-scalar type Derived requested时哪个错了?我的编译器或我的书,或者我刚刚被误解了?提前谢谢

1 个答案:

答案 0 :(得分:3)

只是一个提示。

以下代码是否会出现同样的错误?

class base{};
class derived: public base{};

int main()
{
      derived d= base();
}

是?为什么?因为没有从基类到派生类的转换。如果希望编译代码,则应定义此转换。

如何将它添加到派生类?

derived(const base &b){} 

有道理,是吗?