使用=将已定义的父类转换为子类
C++ Convert from defined superclass to subclass using =
我试图做一些东西来定义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++中,如果要传递一个引用或指针,则只能将子类实例作为其父类的实例传递,实际上不能使其成为其父类的实例。
相关文章:
- 从类继承时,继承的类是否会通过父类重新定义继承的变量
- 从父类方法返回子类对象
- c++, 在子类中,如何在没有对象的情况下访问父类的方法?
- 将父类对象强制转换为子类的问题
- 从父类的向量访问子类函数,而无需向下转换
- 使用父类实例化的向下转换对象
- 将对象强制转换为派生类以访问父类的受保护成员
- 将子类的成员函数强制转换为父类
- 将"this"从父类方法转换为子类方法是一种好的做法吗?
- 将参数传递给函数,获取父类参数,而不将参数强制转换为父类
- 模板化函数指针从子类到父类的转换
- 在C++对象中:我应该使用父类强制转换指针,还是应该使用实际类本身进行强制转换
- 强制转换为父类对象而不是引用时会出现哪些不良结果
- 通过将父类强制转换为对子类的引用来提供类的可迭代"views"
- 将父类强制转换为子类以避免冗余
- 通过强制转换第一个字段来安全访问父类
- c++使用继承的父类转换为对象类
- 使用=将已定义的父类转换为子类
- 在c++中将父类转换为子类
- 在其中删除对象并将对象转换回父类的成员