mau*_*hez 2 c++ polymorphism inheritance openframeworks
我想创建一个名为 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;
};
Run Code Online (Sandbox Code Playgroud)
这是 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);
}
Run Code Online (Sandbox Code Playgroud)
现在,当我创建我的第一个子对象时,我会执行以下操作:
#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
};
Run Code Online (Sandbox Code Playgroud)
现在在我的 main.cpp 中。我想因为我在创建类时使用了父类的构造函数,所以我可以像这样使用父类的构造函数:
int main {
StartButton *startButton;
ofPoint pos = ofPoint(300,300);
string text = "Start Button"
startButton = new StartButton(text, pos);
}
Run Code Online (Sandbox Code Playgroud)
出于某种原因,当我运行它并在 Button 类中打印 pos 和 text 的值时。它打印字符串但不打印 pos。当信息被初始化时,将信息从子级传递给父级肯定存在问题。
StartButton 只有一个构造函数:
StartButton(): Button(pos, text){};
Run Code Online (Sandbox Code Playgroud)
它试图Button用垃圾初始化基础。您需要一个合适的构造函数StartButton:
StartButton(ofPoint _pos, string _text) : Button(_pos, _text) {}
Run Code Online (Sandbox Code Playgroud)
或者如果你能负担得起 C++11,从Button以下继承构造函数:
using Button::Button;
Run Code Online (Sandbox Code Playgroud)