C ++类内部结构动态分配的方法

时间:2018-04-23 06:18:25

标签: c++ class struct dynamic-allocation

我在为方法中的类中分配(:: operator new)声明的结构时遇到了一些麻烦,因为它得到了一个非nub可读的错误:

error: cannot convert 'Automata::state*' to 'state*' in assignment

\ 我试过删除“Automata ::”声明,放置“this->”和其他随机的事情,没有成功。遵循示例代码;

#include <iostream>
#include <new>

class Automata{
    public:
        struct quintuple{
            struct state *stateStr = NULL;
            int stateSize = 0;
        };
        struct state{
            struct symbol *symbolStr = NULL;
        };
        struct symbol{
            char *state = NULL;
            int stateSize = 0;
        };
        struct quintuple quintupleStr;
        //Functions
        void quintuple(int stateValidCounter);
};

void Automata::quintuple(int stateValidCounter){
    this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
    return;
}

int main(){
    Automata automata; 
    automata.quintuple(5);
    return 0;
}

/*
g++ -std=c++11 example.cpp -o example.out

example.cpp: In member function 'void Automata::quintuple(int)':
example.cpp:23:30: error: cannot convert 'Automata::state*' to 'state*' in assignment
  this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
                              ^
*/

感谢您的关注。

1 个答案:

答案 0 :(得分:2)

嗯,说实话,这是一个悲伤的疲惫事件。 如果他回答,我想接受@Passer By。

答案很简单@Passer在主要部分发表评论。

是代码

#include <iostream>
#include <new>

class Automata{
    public:
        struct quintuple{
            struct state *stateStr = NULL;
            int stateSize = 0;
        };
        struct state{....};
        struct quintuple quintupleStr;
        //Functions
        void quintuple(int stateValidCounter);
};

void Automata::quintuple(int stateValidCounter){
    this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
    return;
}

int main(){
    Automata automata; 
    automata.quintuple(5);
    return 0;
}

只需切换结构代码位置..

class Automata{
    public:
        struct state{....};
        struct quintuple{
            struct state *stateStr = NULL;
            int stateSize = 0;
        };
        struct quintuple quintupleStr;
        ....;
};

我仍然认为编译错误有点误导