将基类实例分配给c++中的派生实例

Assign base class instance to a derived instance in c++

本文关键字:实例 c++ 派生 基类 分配      更新时间:2023-10-16

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

#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!

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

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

更具体地说,使用派生的构造函数来构建从基派生的:

#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;
}