I'm trying to make something to define a storage container for any subclass of Tag
; ie TAG_String
, in the code in the following files:
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;
}
(In that i know there are empty functions; they will be used later)
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
Is there even a way? (I am conviced there is, so if anyone can prove me wrog, that would be a good thing.)
Make a class which contains a reference to the Tag class, eg as follows:
class Container {
public:
Container( Tag *tag ) {
containedTag = tag;
}
Tag *containedTag;
};
Then instantiate it as follows:
TAG_String tag = TAG_String( "String!" );
Container container = Container( &tag );
I've noticed you have attempted to do something similar with the TAG_Compound class, however the vector is only accepting Tag values, and would need to accept a pointer or a reference instead. Remember, in C++, you can only pass a child class instance off as an instance of its parent class if you're passing a reference or pointer to it, you cannot actually make it an instance of the parent class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.