首页 > 解决方案 > 为什么当我在超类中打印并在派生类中扩展此函数时,它在 C++ 中不显示特定属性?

问题描述

我有这个枚举类:

class Artifact{
public:
    enum class artifactType{vase,jewelry,partialRelic,unknown};
...

在这堂课中,我制作了这个打印功能:

 void print(std::ostream& os){
        os<<"discoveryDate_:"<<discoveryDate_<<"-"<<"estimatedDateOfOrigin_:"<<estimatedDateOfOrigin_<<"-"<<"Enum that i dont know how to print:"<<"-----";
    }

首先,我不知道如何打印这个枚举,其次,我有 2 个继承这个类的派生类:

class GreekArtifact : public Artifact{
private:
    std::string nameOfGod_; //specific attribute 
}

这个打印不工作

 void print(std::ostream& os) {
        Artifact::print(os);
        os <<" God:"<<nameOfGod_;
    }

我没有错误,但它只是没有显示 nameOfGod,因为在 main 中我创建了一个工件列表,当我打印时它显示 Artifact 类打印中的内容,而不是特定属性。我重载了运算符 <<

std::ostream& operator<<(std::ostream& os,const std::list<Artifact>& b){
    for(auto it : b){
        it.print(os);
        os<<"\n";
    }
    return os;
}

标签: c++classprintingderived-class

解决方案


推荐阅读