How to move a structure to a class?

I have something like:

typedef struct Data_s {
  int field1;
  int field2;
} Data;

class Foo {
  void getData(Data& data);
  void useData(Data& data);
}

In another class function, I can:

class Bar {
  Data data_;
  void Bar::taskA() {
    Foo.getData(data_);
    Foo.useData(data_);
  }
}

Is there a way to move data from a global scope and to Foo without creating a new class? The data reflects the structure existing in the library that I use elsewhere. (i.e. the same fields, just a different name. I passed the data to a different structure later. I do this because Foo is an abstract class, and a derived class using the library is just one of many.)

For now, just inserting it inside the class and replacing Datawith Foo::Dataeverywhere doesn't work.

class Foo {
  typedef struct Data_s {
    int field1;
    int field2;
  } Data;
  ...
}

I get 'Data' in class 'Foo' does not name a typeinBar data_;

+3
source share
2 answers

, , . , , :

class Foo
{
public:
    struct Data
    {
        int field1;
        int field2;
    };

    void getData(Foo::Data& data) {}
    void useData(Foo::Data& data) {}
};

void UseFooData()
{
    Foo::Data bar;
    Foo f;
    f.getData(bar);
    f.useData(bar);
}

: /, . , , Foo, Data public, Foo::Data.

+4

, Foo:: Data , . .

-, ++, typedef ( , ).

Try this patched version:

class Foo {
public:
  struct Data {
    int field1;
    int field2;
  };
  ...
}
+2
source

Source: https://habr.com/ru/post/1738894/


All Articles