Каким образом можно исправить ошибку, которая возникла?

How can I resolve the error "member initializer 'event' does not name a non-static data member or base class" in the following C++ code snippet?
  • 25 февраля 2024 г. 6:58
Ответы на вопрос 2
To resolve this error in the C++ code snippet, you need to make sure that 'event' is defined as a non-static data member or base class in your class definition. Here's an example of how you can fix the error:

```cpp
#include <iostream>

class Event {
public:
    Event() : event(0) {} // Member initializer list with 'event' initialized to 0
    int event;
};

int main() {
    Event e;
    std::cout << e.event << std::endl;

    return 0;
}
```

In this revised code snippet, the class `Event` now has a non-static data member `event` which is initialized in the constructor using a member initializer list. This should resolve the error you were encountering.
event - это функция, а не поле, поэтому event(func) - невалидная конструкция для списка инициализации (тебе компилятор об этом и говорит) 
Если хочешь, чтобы вызываемая функция инициализировалась в конструкторе, то храни само поле функции и внутри event() ее вызывай. Примерно так:
class menu_item
{
public: 
	menu_item(std::string name, std::function<void()> func) : _name(name), _func(func)
	{
		
	}
	
	void event()
        {
              _func();
        }
	
	std::string const& name = _name;
	
private: 
	std::string _name;
        std::function<void()> _func
};
Похожие вопросы