我在C 中工作。
我的类animation.h
是:
class Animation
{
public:
Animation(ofVec2f _startLoc, ofVec2f _endLoc, float _speed, float _accel);
virtual ~Animation();
};
然后在sceneMusic.h
中我有另一个称为animation
类的类。
#include "animation.h"
class sceneMusic
{
public:
sceneMusic();
virtual ~sceneMusic();
private:
Animation staveMotion;
};
和sceneMusic.cpp
sceneMusic::sceneMusic()
{
staveImg.loadImage("./sceneMusic/stave_white.png");
staveMotion = Animation(ofVec2f(29, -staveImg.height()),
ofVec2f(29, 249), 1, 0.1);
}
上面给出以下(预期)错误:
src/awards/sceneMusic.cpp|3|error: no matching function for call to ‘Animation::Animation()’|
src/awards/sceneMusic.cpp|5|note: candidates are:|
src/Animation.h|14|note: Animation::Animation(ofVec2f, ofVec2f, float, float)|
src/Animation.h|14|note: candidate expects 4 arguments, 0 provided|
我读了很多线程,这些线程建议我应该使用 initializer lists
并在 sceneMusic.cpp
sceneMusic::sceneMusic()
:Animation(ofVec2f(29, -staveImg.height()),
ofVec2f(29, 249), 1, 0.1)
{
staveImg.loadImage("./sceneMusic/stave_white.png");
}
或类似的东西。问题是只有在执行构造函数后,Staveimg的height
才会可用。
sceneMusic
类也不继承animation
类,因此我不确定上述如何工作。如果我尝试运行以上,我会得到
src/awards/sceneMusic.cpp|4|error: type ‘Animation’ is not a direct base of ‘sceneMusic’|
src/awards/sceneMusic.cpp|4|error: ‘((sceneMusic*)this)->sceneMusic::staveImg.ofImage_<unsigned char>::height’ cannot be used as a function|
src/awards/sceneMusic.cpp|5|error: no matching function for call to ‘Animation::Animation()’|
src/awards/sceneMusic.cpp|5|note: candidates are:|
...
我在做什么错?
谢谢您的帮助
好吧,第二次尝试的问题是您需要这样做:
sceneMusic::sceneMusic()
:staveMotion(ofVec2f(29, -staveImg.height()),
ofVec2f(29, 249), 1, 0.1)
您在初始化器列表中指定成员名称。仅当您尝试调用特定的超级级构造函数时,才会指定一个类名称。Animation
不是sceneMusic
的超级级别。
以下"无匹配函数call to Animation :: Animation()出现,如果您根本没有任何初始化列表中没有任何内容,则会发生相同的原因:staveMotion
成员仍在尝试使用 Animation
s默认构造函数(就像声明变量Animation a;
时使用默认构造函数一样),但是Animation
没有默认的构造函数。
纠正初始化器列表中的错误会处理两个错误。
顺便说一句,您关于height()
的第二个错误:确保实际上有一个名为height()
的成员函数。您没有显示代码,但该错误似乎表明您实际上具有 variable 名为 height
而不是函数。
但是,以上仍然不会第一次致电loadImage
(感谢Chris在评论中提醒我)。
最简单的解决方案是恢复您的第一次尝试,并为Animation
提供默认(无参数)构造函数。一旦您声明非默认构造函数,编译器就不再为您生成默认的构造函数,并且必须明确声明/定义Animation::Animation()
以提供它。这样,staveMotion
可以用一些默认值构造(不必在您的初始化器列表中构造),然后分配给适当的值。
第二个选项不需要创建临时默认的 Animation
s(或更重要的是,更重要的是,您不需要您实现可能破坏类别不变的默认构造函数)staveImg
是sceneMusic
的成员字段,为其提供一个构造函数,该构造器以图像文件名并加载图像,并在成员列表中的staveMotion
之前声明它。您不需要Animation
默认构造函数,并且可以初始化初始化器列表中的所有内容:
sceneMusic :: sceneMusic () :
staveImg("./sceneMusic/stave_white.png"),
staveMotion(ofVec2f(29, -staveImg.height()), ofVec2f(29, 249), 1, 0.1)
{
}
该选项上的一个变化是提前构造图像,并将其作为参数传递给sceneMusic
构造函数。这不需要新的构造函数fo staveImg
。
在评论中提出的第三个选项是使staveMotion
成为指针。您可以将其初始化为NULL
并在必要时构造new Animation(...)
,而无需默认构造函数。如果这样做,请不要忘记完成delete
。自动指针,例如std::unique_ptr<Animation>
或其他智能指针之一(boost
也有一些)可以使您更容易。
您需要一个默认构造函数类动画,因为您提供参数构造函数,因此编译器不会为您生成一个
Animation() {}