简体   繁体   English

使用Parent构造函数初始化子类

[英]Using the Parent constructor to initialize a child class

I want to create a general class called Button that others inherit from, so that for example I can have StartButton, ContinueButton, etc. There are certain values regardless of the different properties that I want to start with the constructor since they will always be needed so I built my own Button Class like this: 我想创建一个名为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;

};

This is the implementation Button.cpp: 这是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);
}

Now, when I create my first child object I do the following: 现在,当我创建我的第一个子对象时,我执行以下操作:

#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

};

Now in my main.cpp. 现在在我的main.cpp中。 I thought because I was using the parent's constructor when creating the class I would be able to use the constructor of the parent like this: 我想因为我在创建类时使用了父的构造函数,我可以像这样使用父类的构造函数:

int main {
  StartButton *startButton;
  ofPoint pos = ofPoint(300,300);
  string text = "Start Button"
  startButton = new StartButton(text, pos); 
}

For some reason when I run it and prints the values of the pos and text in the Button class. 出于某种原因,当我运行它并在Button类中打印pos和text的值时。 It prints the string but not the pos. 它打印字符串但不打印pos。 There's definitely an issue passing the information from the child to the parent when the information gets initialized. 在信息初始化时,将信息从孩子传递给父母肯定存在问题。

StartButton only has one constructor: StartButton只有一个构造函数:

StartButton(): Button(pos, text){};

which attempts to initialize the base Button with garbage. 它试图用垃圾初始化基本Button You need a proper constructor for StartButton : 你需要一个适当的StartButton构造StartButton

StartButton(ofPoint _pos, string _text) : Button(_pos, _text) {}

or if you can afford C++11, inheriting the constructors from Button : 或者,如果你能买得起C ++ 11,继承Button的构造函数:

using Button::Button;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM