使用返回类型作为指向派生类的指针 [英] using the return type as pointer to derived class

查看:195
本文介绍了使用返回类型作为指向派生类的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能在基类中有一个函数,它将返回类型作为指向派生类的指针?主要目的是在以后使用 Base Derived Class设置值。

Is it possible to have a function in base class which will have return type as pointer to derived class? the main objective is for later use where you use Base and Derived Class to set values.

Base B1;
B1.SetName("nameOfBase");
Derived* D1 = B1.CreateDerived("DerivedFromBase");//CreateDerived method will be in class Base
D1->SetMinPoint(0,1);//this method will be implemented in derived class
D1->SetMaxPoint(4,4);//this method will be implemented in derived class

我在实现中遇到问题,我做了像

I am having problem in implementation, i did something like

class Base
{
public:
  Base();
  bool SetName(char*);//or SetName(string)
  Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
  ~Base();
protected:
  char baseName[20];// or string baseName
  Derived* derivedPtr[5];
};

class Derived: public Base
{
public:
  Derived();
  bool SetName(char*);//the name given in Derived* CreateDerived(char*) will be set here
  ~Derived(); 
};

当我尝试这样做和运行程序,我得到错误像

when i try to do this and run the program i get errors like

// Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
error C2143: syntax error: missing ';' before '*'
error C4430: missing type identifier: int assumed.


推荐答案

它似乎是一个有点问题的设计,但没有什么阻止你这样做。您只需要在引用之前声明类 Derived

Yes, it's possible. It seems to be a somewhat questionable design, but there's nothing preventing you from doing it. You just need to declare class Derived before you refer to it:

class Derived;  //forward declaration here

class Base
{
public:
  Base();
  bool SetName(char*);//or SetName(string)
  Derived* CreateDerived(char*); // or Derived* CreateDerived(string)
  ~Base();
protected:
  char baseName[20];// or string baseName
  Derived* derivedPtr[5];
};

class Derived: public Base
{
public:
  Derived();
  bool SetName(char*); //don't forget semi-colon
  ~Derived(); 
};

并且像@psur提到的,你也缺少一个分号 SetName

And as @psur mentioned, you were also missing a semi-colon after SetName.

我强烈建议使用 std :: string code> char * 用于C ++中的字符串。

And I do strongly suggest using std::string instead of char* for strings in C++.

这篇关于使用返回类型作为指向派生类的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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