大家好,我是新来的,在嵌套类中声明构造函数时出现错误。
假设我有一个名为 Event 的类,有 2 个继承它的嵌套类,SampleEvent 和 TimeEvent,在 SampleEvent 和 TimeEvent 构造函数中,有一个错误。
这是我的代码:
// Event Class
#ifndef EVENT_H
#define EVENT_H
#include <iostream>
namespace Engine
{
namespace Data
{
class Event
{
public:
// Class Variable
int Measure;
int Beat;
int Position;
// This Class that was I mean
class SampleEvent;
class TimeEvent;
// Constructor
Event(int measure, int beat, int pos);
};
// Sample Event Class
class Event::SampleEvent : public Event
{
public:
// variable in SampleEvent Class
int ID;
float Pan;
float Vol;
// Constructor
SampleEvent(int id, float pan, float vol, int measure, int beat, int pos);
};
// Time Event Class
class Event::TimeEvent : public Event
{
public:
// variable in TimeEvent Class
double Value;
// Constructor
TimeEvent(double value, int measure, int beat, int pos);
};
// Constructor of Event
Event::Event(int measure, int beat, int pos)
{
Measure = measure;
Beat = beat;
Position = pos;
}
// Constructor of Sample Event
Event::SampleEvent::SampleEvent(int id, float pan, float vol, int measure, int beat, int pos) : Event::Event(measure, beat, pos)
{
ID = id;
Pan = pan;
Vol = vol;
Measure = measure;
Beat = beat;
Position = pos;
}
// Constructor of Time Event
Event::TimeEvent::TimeEvent(double value, int measure, int beat, int pos) : Event::Event(measure, beat, pos)
{
Value = value;
Measure = measure;
Beat = beat;
Position = pos;
}
}
}
#endif
这给我 2 个错误:
Error C2039: '{ctor}' : is not a member of 'Engine::Data::Event' (line 60)
Error C2039: '{ctor}' : is not a member of 'Engine::Data::Event' (line 71)
有人可以帮助我吗? 谢谢
最佳答案
int Position
缺少一个分号。
此外,您在代码末尾缺少右括号:
}
} // <--- MISSING
}
但是,代码的主要问题是您需要显式初始化基类构造函数,因为自从您定义了构造函数 Event(int measure, int beat, int pos);
.
Event::SampleEvent::SampleEvent(int id, float pan, float vol,
int measure, int beat, int pos)
: Event(id, id, id) // This is just an example, pass the proper values here
{
//...
}
Event::TimeEvent::TimeEvent(double value, int measure, int beat, int pos)
: Event(measure, measure, measure) // Pass the proper values to base ctor
编辑
现在的错误是因为你使用了 Event::Event(measure, beat, pos)
而不是 Event
。 (但是,我认为 Event::Event
应该 工作,我认为这是 MSVC 中不接受代码的错误。)
关于继承嵌套类时C++错误C4091,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628645/