C++ 使用多态性复制派生类';基类的值

C++ 使用多态性复制派生类';基类的值,c++,class,C++,Class,英语不是我的第一语言。我希望我不会犯很多错误。我会尽我最大的努力把事情弄清楚 我有一个基础班 class engine { private : std::string name; double weight; public: engine(); ~engine(); std::string getName() const; int getWeight() const }; std::string engine::getName() const{

英语不是我的第一语言。我希望我不会犯很多错误。我会尽我最大的努力把事情弄清楚

我有一个基础班

class engine
{
private :
    std::string name;
    double weight;

public:
    engine();
    ~engine();
    std::string getName() const;
    int getWeight() const
};

std::string engine::getName() const{
return this->name;
}

int engine::getWeight() const{
return this->weight;
}
和派生类

class diesel : public engine
{
private:
    std::string name;
    double weight;

public:
    diesel();
    ~diesel();
};

diesel::diesel(){
this->name = Diesel;
this->weight = 500.00;
}
在我的main.cpp中

int main()
{
      diesel diesel_engine; 
      const engine &e = diesel_engine;
      std::cout<<e.getWeight()<<e.getName()<<std::endl;
      return 0;
}
intmain()
{
柴油机;
恒速发动机&e=柴油发动机;

std::cout让我们从类声明开始

class Engine
{
private:
    float weight_;
    std::string name_;
public:
    Engine(float weight, std::string name) : weight_(weight), name_(name){};
    std::string GetName() const { return name_;}
};

class Diesel : public Engine
{
public:
  Diesel(float weight, std::string name) : Engine(weight, name){} 
};
所以我们这里有一个
引擎
类,它是我们的
基类
,然后我们定义我们的
柴油类
柴油
继承自
引擎
,并将参数传递给它的基类

现在使用这个:

Diesel disel_engine(0.0, "diesel engine");
const Engine& eng = disel_engine;
cout << eng.GetName();
柴油柴油机(0.0,“柴油机”); const Engine&eng=柴油机;
如果能添加类声明那就太好了。好的,我会的!谢谢你,我不太确定我是否真的理解了;似乎成员变量
name
weight
应该有
protected
修饰符,而不是在派生类中重新声明。会发生什么?会出现编译时错误、运行时错误吗,如何检查
main
末尾的
发动机的值?“当我调用const-engine&e=diesel\u-engine;时,应将diesel\u发动机的值(名称和重量)复制到新的发动机e。”-<代码> E <代码>是一个引用,不是一个新的对象,没有任何东西被复制。@ JePijull我感到困惑,因为当我调用CONST引擎和E= DeCeleLoMeX引擎时,我不是制造一个新引擎吗?非常感谢你回答我的问题!现在我知道如何使用它!!谢谢!我建议推荐一本好的C++书籍,并且完全理解这一点。作品