【问题标题】:Using the Parent constructor to initialize a child class使用 Parent 构造函数初始化子类
【发布时间】: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


【解决方案1】:

StartButton 只有一个构造函数:

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

它试图用垃圾初始化基础ButtonStartButton 需要一个合适的构造函数:

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

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

using Button::Button;

【讨论】:

  • 我收到以下错误:体系结构 i386 的未定义符号:“按钮的类型信息”,引用自:StartButton.o 中 StartButton 的类型信息“按钮的 vtable”,引用自:Button::~Button () in ofApp.o 注意:缺少 vtable 通常意味着第一个非内联虚成员函数没有定义。
  • @mauricioSanchez:您是在某处定义Button 的虚函数,还是应该是纯虚函数?
  • 我没有在任何地方定义它
  • @mauricioSanchez:嗯,这就是链接器所抱怨的,这些虚函数没有定义。
  • 这个构造函数 StartButton(ofPoint _pos, string _text) : Button(_pos, _text) {} 是否必须在 StartButton.cpp 中定义?
猜你喜欢
  • 1970-01-01
  • 2013-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多