小编Nik*_*den的帖子

Haskell,类中的函数声明

我试图为多态类树创建一些实例,但我不明白,

看,我的代码是:

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)

polymorphism haskell class instance

4
推荐指数
1
解决办法
128
查看次数

分配Union的字段

我创建了一个结构使用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)

设置值我收到错误(分段错误(核心转储))这样做的正确方法是什么?谢谢!

c++ setter struct unions

3
推荐指数
1
解决办法
517
查看次数

标签 统计

c++ ×1

class ×1

haskell ×1

instance ×1

polymorphism ×1

setter ×1

struct ×1

unions ×1