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

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.
<code>event</code> - это функция, а не поле, поэтому <code>event(func)</code> - невалидная конструкция для списка инициализации (тебе компилятор об этом и говорит) <br/> Если хочешь, чтобы вызываемая функция инициализировалась в конструкторе, то храни само поле функции и внутри <code>event()</code> ее вызывай. Примерно так: <br/> <pre><code class="cpp">class menu_item
{
public: 
	menu_item(std::string name, std::function&lt;void()&gt; func) : _name(name), _func(func)
	{
		
	}
	
	void event()
        {
              _func();
        }
	
	std::string const&amp; name = _name;
	
private: 
	std::string _name;
        std::function&lt;void()&gt; _func
};</code></pre>
Похожие вопросы