使用=将已定义的父类转换为子类

C++ Convert from defined superclass to subclass using =

本文关键字:父类 转换 子类 定义 使用      更新时间:2023-10-16

我试图做一些东西来定义Tag的任何子类的存储容器;即TAG_String,在以下文件的代码中:

main.cpp

#include <iostream>
#include "Tag.h"
using namespace std;
int main() {
    nbt::TAG_Compound d("Data");
    d["str"] = new nbt::TAG_String("str");
    d["str"].value("hi");
    cout << d["str"].value() << endl;
    //cout << val() << endl;
    return 0;
}

Tag.cpp

#include "Tag.h"
using namespace std;
nbt::Tag::Tag(string nam){
    name = nam;
}
/*nbt::Tag& nbt::Tag::operator=(nbt::Tag& nw){
    nbt::Tag *tis = this;
    tis = nw;
    return tis&;
}*/
string nbt::Tag::Name(){
    return name;
}
void nbt::Tag::Name(string nam){
    name = nam;
}
void nbt::TAG_Compound::load(string file){
}
void nbt::TAG_Compound::save(string file){
}
nbt::Tag& nbt::TAG_Compound::operator[](string lookup){
    for(int i=0;i<val.size();i++){
        if(val[i].Name() == lookup){
            return val[i];
        }
    }
    nbt::Tag tag("");
    val.push_back(tag);
    return val[val.size()-1];
}
void nbt::TAG_String::load(string file){
}
void nbt::TAG_String::save(string file){
}
string nbt::TAG_String::value(){
    return val;
}
void nbt::TAG_String::value(string v){
    val = v;
}

(我知道有空函数;它们将在以后使用)

Tag.h

#ifndef NBTTAG_H_INCLUDED
#define NBTTAG_H_INCLUDED
#include <string>
#include <vector>
namespace nbt{
    class Tag {
        std::string name;
    public:
        //void save(std::string);
        //void load(std::string);
        std::string Name();
        void Name(std::string);
        Tag(std::string);
        //Tag& operator=(Tag&);
    };
    class TAG_Compound : public Tag {
        std::vector<Tag> val;
    public:
        void save(std::string);
        void load(std::string);
        Tag& operator[](std::string);
        using Tag::Tag;
    };
    class TAG_String : public Tag {
        std::string val;
    public:
        void save(std::string);
        void load(std::string);
        std::string value();
        void value(std::string);
        using Tag::Tag;
    };
}
#endif // NBTTAG_H_INCLUDED

有办法吗?(我相信有,所以如果有人能证明我错了,那将是一件好事。)

创建一个类,其中包含对Tag类的引用,例如:

class Container {
public:
    Container( Tag *tag ) {
        containedTag = tag;
    }
    Tag *containedTag;
};

然后按如下方式实例化:

TAG_String tag = TAG_String( "String!" );
Container container = Container( &tag );

我注意到您已经尝试对TAG_Compound类做类似的事情,但是向量只接受Tag值,而需要接受指针或引用。请记住,在c++中,如果要传递一个引用或指针,则只能将子类实例作为其父类的实例传递,实际上不能使其成为其父类的实例。