将基类实例分配给c ++

时间:2015-10-31 13:08:43

标签: c++

我尝试使用基类实例初始化派生类的实例。我之所以这样做,是因为我不得不使用基类中已有的数据来初始化我的派生类。我不能使用构造函数在派生类中初始化这些字段我希望有这样的东西:

#include<iostream>
#include<vector>

using namespace std;

class Base {
protected:
    int i;

public:
    //Base(const Base&) {/*...*/}

    Base(int &in):i(in){}

    Base& operator=(const Base &src) {
        i = (src.i);
        return *this;
    }

    void display(){ cout<<i<<endl;/*display the content of i*/ }
};

class Derived: public Base {
protected:
    int j;

public:
    //Derived(const Base& b) : Base(b) {}

    using Base::operator=;

    Derived& operator=(const Derived &src) {
        *this = static_cast<const Base&>(src);
        j = (src.j);
        return *this;
    }

    // additional method trying to modify b::j and preferably b::i ?
    void setJ(int& f){i=f;}
};

int main() {
    int a =1;
    int b=2;

    Base* base = new Base(a);
    Derived* derived;

    *derived=*base; // this should initialize derived::i with base::i in the     best case and make a copy in derived::j if there is no possible         access to modify derived.i//
    derived->setJ(b);
    derived->display();

    return 0;
}

输出:分段错误(核心转储)

要求:无法使用ij字段上的构造函数初始化派生类,因为我在基类中的字段Base.i上没有getter / setter!

2 个答案:

答案 0 :(得分:0)

  

我正在尝试使用实例初始化派生类的实例   基类。

Base::Base(const Base&) {/*...*/}

Derived::Derived(const Base& b) : Base(b) {}

答案 1 :(得分:0)

更具体地说,使用derived的构造函数来构建派生自base:

#include<iostream>

class Base {
protected:
    int i;

public:
    Base(int &in) : i(in) {}

    void display() {
        std::cout << i << std::endl;
    }
};

class Derived: public Base {
public:

    Derived(const Base &b) : Base(b) {}

    void setJ(int &f){ i = f; }
};

int main() {
    int a = 1, b = 2;

    Base base(a);
    Derived derived(base);

    derived.setJ(b);
    derived.display();

    return 0;
}