gpt4 book ai didi

c++ - 使用返回类型作为派生类的指针

转载 作者:行者123 更新时间:2023-11-28 07:42:09 26 4
gpt4 key购买 nike

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

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

我在实现中遇到了问题,我做了类似的事情

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();
};

当我尝试执行此操作并运行程序时,出现类似

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

最佳答案

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

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 后的分号。

而且我强烈建议在 C++ 中对字符串使用 std::string 而不是 char*

关于c++ - 使用返回类型作为派生类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15611959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com