定义之前的结构声明

Struct declaration before definition

本文关键字:结构 声明 定义      更新时间:2023-10-16

我的C++代码有一个小问题。

class Command {
public:
    virtual void start(CommandDesc userinput, Converter* convertobj) = 0;
    virtual void help(int option) = 0;
};

struct CommandDesc
{
    std::string name;
    std::string description;
    Command* comobj;   //Issue is here
};

如果我在类之前定义结构,我将无法定义成员

Command* comobj; 

如果我在类之后定义,我将无法将结构的实例传递给具有的方法

virtual void start(CommandDesc userinput, Converter* convertobj) = 0;

你能提出什么建议?有没有什么方法可以先声明结构,而不是单独定义它?

好的,如果我在上课前定义结构,我将无法定义成员

Command* comobj;

由于comobj是一个指针,因此可以转发声明Command来解决此问题。

你可以这样做:

class Command;
struct CommandDesc
{
    std::string name;
    std::string description;
    Command* comobj; 
};
class Command {
public:
    virtual void start(CommandDesc userinput, Converter* convertobj) = 0;
    virtual void help(int option) = 0;
};

是-简单-前向声明

只需放入

class Command;
struct CommandDesc
{
 ....
}
class Command {
 As before
};