【发布时间】:2014-09-14 21:19:14
【问题描述】:
我想创建一个名为 Button 的通用类,其他人从中继承,例如,我可以拥有 StartButton、ContinueButton 等。无论我想从构造函数开始的不同属性如何,都有某些值,因为它们会总是需要,所以我像这样构建了自己的按钮类:
#pragma once
#include "ofMain.h"
class Button {
public:
Button(ofPoint _pos, string _text);
virtual void setup();
virtual void update();
virtual void draw();
protected:
ofTrueTypeFont buttonName;
ofPoint pos;
string text, fontName;
bool isClicked;
int buttonFader, buttonFaderVel;
};
这是Button.cpp的实现:
#include "Button.h"
Button::Button(float _pos, string _text): pos(_pos), text(_text){
cout << pos << endl;
cout << text << endl;
}
void Button::setup(){
fontSize = 19;
fontName = "fonts/GothamRnd-Medium.otf";
buttonName.loadFont(fontName, fontSize);
cout << text << endl;
}
void Button::update(){
}
void Button::draw(){
ofSetColor(255);
buttonName.drawString(text, pos ,pos);
}
现在,当我创建我的第一个子对象时,我会执行以下操作:
#include "Button.h"
class StartButton: public Button{
public:
StartButton(ofPoint _pos, string _text): Button(_pos, _text){};//This is how I use the parent's constructor
};
现在在我的 main.cpp 中。我想因为我在创建类时使用了父类的构造函数,所以我可以像这样使用父类的构造函数:
int main {
StartButton *startButton;
ofPoint pos = ofPoint(300,300);
string text = "Start Button"
startButton = new StartButton(text, pos);
}
由于某种原因,当我运行它并在 Button 类中打印 pos 和 text 的值时。它打印字符串但不打印 pos。当信息被初始化时,将信息从子代传递给父代肯定存在问题。
【问题讨论】:
-
根本没有任何
StartButton构造函数接受参数 -
so 如何将值传递给 StartButton?
-
如果您想将参数传递给基类的构造函数,您还需要将这些参数提供给派生类。您的派生类的构造函数不接受任何参数。
-
所以基本上有了这样的东西,参数将一直传递给父类: StartButton(ofPoint _pos, string _text): Button(pos, text){}; ?
-
如果参数被称为
_pos,那么您将把_pos传递给基本构造函数。
标签: c++ inheritance polymorphism openframeworks