访问未声明的结构?

Zac*_*ere 2 c++

我有办法访问尚未声明的结构吗?

//Need to some how declare 'monitor' up here, with out moving 'monitor' above 'device'
//because both structs need to be able to access each others members

struct{
    int ID = 10;
    int Get__Monitor__ID(){
        return monitor.ID; //obvioulsly 'monitor' is not declared yet, therefore throws error and is not accessible
    }
} device;

struct{
    int ID = 6;
    int Get__Device__ID(){
        return device.ID; //because 'device' is declared above this struct, the ID member is accessible
    }
} monitor;
Run Code Online (Sandbox Code Playgroud)

Bil*_*nch 5

在这种特殊情况下,您可以在结构体中定义函数原型,定义可以稍后来。

struct device_t {
    int ID = 10;
    int Get__Monitor__ID();
} device;

struct monitor_t {
    int ID = 6;
    int Get__Device__ID();
} monitor;

int device_t::Get__Monitor__ID() {
  return monitor.ID;
}

int monitor_t::Get__Device__ID() {
  return device.ID;
}
Run Code Online (Sandbox Code Playgroud)

  • 您可能想要添加“内联”,除非将函数移至 CPP 文件。并且只需要修改第一个函数。 (3认同)