[英]Using the Parent constructor to initialize a child class
我想創建一個名為Button的通用類,其他人繼承,所以例如我可以有StartButton,ContinueButton等。無論我想從構造函數開始的不同屬性都有某些值,因為它們總是需要它們所以我建立了我自己的Button類,如下所示:
#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
只有一個構造函數:
StartButton(): Button(pos, text){};
它試圖用垃圾初始化基本Button
。 你需要一個適當的StartButton
構造StartButton
:
StartButton(ofPoint _pos, string _text) : Button(_pos, _text) {}
或者,如果你能買得起C ++ 11,繼承Button
的構造函數:
using Button::Button;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.