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

标签 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 将调用基的复制 c'tor 但每次我收到 从 Base 到非标量的转换type Derived requested 谁错了?我的编译器或我的书,还是我误解了?提前致谢

最佳答案

只是一个提示。

下面的代码是否给出同样的错误?

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

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

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

如何将其添加到派生类?

derived(const base &b){} 

有道理吧?

关于c++ - 基类和派生类的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3849140/

相关文章:

c++ - Qt Visual Studio 2008插件问题

c++ - 如何获取异步读取时传输的字节数boost asio c++

c++ - 将指向对象的指针 vector 传递给另一个对象的成员函数的问题

c++ - 在 C++ 中访问多维数组的整行

c++ - 如何解决负数情况下程序以相同方式工作的问题?

c++ - 输入、输出、输入/输出参数

c++ - 在不同 CPU 上处理整数

c++ - 从 COM TypeLib 自动生成的 C++ 类不会在方法中返回 SAFEARRAY

c++ - 并行实例化类导致与内存相关的错误

c++ - 未定义对 avcodec_alloc_context 的引用但 ffmpeg 链接器顺序正确吗?