将基类实例分配给c++中的派生实例
Assign base class instance to a derived instance in 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;
}
输出:分段故障(堆芯转储)
要求:无法在i
或j
字段上使用构造函数初始化派生类,因为我在基类中的字段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;
}
相关文章:
- 从C++实例化QML
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- OpenGL - 在抛出"__gnu_cxx::recursive_init_error"实例后终止调用?
- 如何在c++中为模板函数实例创建快捷方式
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 无法创建抽象类的实例
- 多个文件的内存分配错误"在抛出 'std :: bad_alloc' what (): std :: bad_alloc 的实例后终止调用" [C++]
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 我收到以下错误:抛出'std::bad_alloc'实例后终止调用
- 建议在运行时将带有类实例的列表从c++导入qml
- 约束和显式模板实例化
- 通过实例理解std::move及其目的
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 有没有一种"cleaner"的方法可以在指向基的指针向量中找到派生类的第一个实例?
- 正在生成未知类实例
- 从DLL中删除类的实例
- 在std::vector上存储带有模板的类实例
- 为什么创建友元类的实例会导致"undefined reference to"错误?