使用Parent构造函数初始化子类 [英] Using the Parent constructor to initialize a child class

查看:159
本文介绍了使用Parent构造函数初始化子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个名为Button的通用类,其他人继承,所以例如我可以有StartButton,ContinueButton等。无论我想从构造函数开始的不同属性都有某些值,因为它们将总是需要所以我建立了我自己的Button类:

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:

#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:

This is the implementation 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

};

现在在我的main.cpp中。我想因为我在创建类时使用了父的构造函数,我可以像这样使用父类的构造函数:

Now in my 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); 
}

出于某种原因,当我运行它并打印pos和text的值时在Button类中。它打印字符串但不打印pos。在信息初始化时,将信息从孩子传递给父母肯定存在问题。

For some reason when I run it and prints the values of the pos and text in the Button class. It prints the string but not the pos. There's definitely an issue passing the information from the child to the parent when the information gets initialized.

推荐答案

StartButton 只有一个构造函数:

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

尝试初始化基本按钮垃圾。你需要一个适当的构造函数 StartButton

which attempts to initialize the base Button with garbage. You need a proper constructor for StartButton:

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

或者如果你买得起C ++ 11 ,使用Button :: Button从 Button 继承构造函数:

or if you can afford C++11, inheriting the constructors from Button:

using Button::Button;

这篇关于使用Parent构造函数初始化子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆