我试图为多态类树创建一些实例,但我不明白,
看,我的代码是:
data BTree a = BLeaf a | BBranch a (BTree a) (BTree a) deriving(Show)
data TTree a = TLeaf a | TBranch a (TTree a) (TTree a) (TTree a) deriving(Show)
class Tree a where
getName :: a -> a -- How should i declare this function?
instance Tree (BTree a) where
getName (BLeaf name) = name
getName (BBranch name lhs rhs) = name
instance Tree (TTree a) where
getName (TLeaf name) = name
getName (TBranch name lhs mhs …Run Code Online (Sandbox Code Playgroud) 我创建了一个结构使用union作为其字段.这是一个小代码示例:
#include <iostream>
#include <string>
enum Type
{
STR,
INT
};
struct MyStruct
{
Type type;
union Value
{
std::string str;
int i;
Value(){}
~Value(){};
} value;
void setType(Type type)
{
this->type = type;
}
void setValue(const std::string& data)
{
this->value.str = data;
}
MyStruct(){}
~MyStruct(){}
};
int main()
{
MyStruct my;
my.setType(Type::STR);
my.setValue("Hallo");
std::cout << my.value.str << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
设置值我收到错误(分段错误(核心转储))这样做的正确方法是什么?谢谢!