【问题标题】:C++: How can I forward-declare derived classes that appear in a static method of a base class?C++:如何前向声明出现在基类的静态方法中的派生类?
【发布时间】:2021-10-18 16:13:10
【问题描述】:

只是做一个简单的练习,我将从另一种语言中学到的想法翻译成 C++。

我有一个抽象类 Number,它有两个派生类,PositiveNumber 和 NegativeNumber。 Number 有一个静态方法应该创建一个 PositiveNumber 或 Negative number 的新实例,具体取决于其输入的符号。

#include <iostream>

class Number
{
public:
protected:
    int magnitude_;
public:
    static Number* fromInt(int x)
    {
        if (x >= 0) { return new PositiveNumber(x); }
        else        { return new NegativeNumber(x); }
    }
    int getMagnitude() { return magnitude_; }
    virtual void print() = 0;
};

class PositiveNumber: public Number
{
protected:
public:
    PositiveNumber(int magnitude) { magnitude_ = magnitude; }
    void print() { std::cout << magnitude_ << "\n"; }
};

class NegativeNumber: public Number
{
protected:
public:
    NegativeNumber(int magnitude) { magnitude_ = magnitude; }
    void print() { std::cout << "-" << magnitude_ << "\n"; }
};


int main (int argc, char* argv[])
{
    Number* x = Number::fromInt(5);
    x->print();

    return 0;
}

我知道我需要告诉 Number PositiveNumber 和 NegativeNumber 存在,但我不知道该怎么做。我尝试添加

class PositiveNumber;
class NegativeNumber;

在 Number 的定义之前,但这还不够,导致:

use of undefined type 'PositiveNumber'
use of undefined type 'NegativeNumber'

我确信这有一个简单的答案,但我对调试 C++ 的东西还很陌生,所以我很迷茫。感谢阅读。

【问题讨论】:

    标签: c++ derived-class forward-declaration


    【解决方案1】:

    fromInt()的定义需要知道PositiveNumberNegativeNumber有哪些构造函数,所以前向声明是不够的。你需要把Number::fromInt()的声明和定义分开,然后你可以把定义移到PositiveNumberNegativeNumber的声明下面。

    另外,不要忘记delete fromInt() new 的对象。这也意味着向Number 添加一个虚拟析构函数,以便可以从基本Number* 指针正确调用派生的析构函数。

    试试这个:

    #include <iostream>
    
    class Number
    {
    protected:
        int magnitude_;
    public:
        static Number* fromInt(int x);
    
        virtual ~Number() {}
    
        int getMagnitude() { return magnitude_; }
        virtual void print() = 0;
    };
    
    class PositiveNumber: public Number
    {
    public:
        PositiveNumber(int magnitude) { magnitude_ = magnitude; }
        void print() { std::cout << magnitude_ << "\n"; }
    };
    
    class NegativeNumber: public Number
    {
    public:
        NegativeNumber(int magnitude) { magnitude_ = magnitude; }
        void print() { std::cout << "-" << magnitude_ << "\n"; }
    };
    
    Number* Number::fromInt(int x)
    {
        if (x >= 0) { return new PositiveNumber(x); }
        else        { return new NegativeNumber(x); }
    }
    
    int main (int argc, char* argv[])
    {
        Number* x = Number::fromInt(5);
        x->print();
        delete x;
    
        return 0;
    }
    

    Online Demo

    【讨论】:

      猜你喜欢
      • 2010-10-10
      • 2015-02-01
      • 1970-01-01
      • 2020-06-04
      • 2011-11-18
      • 2012-05-24
      • 2012-06-25
      • 1970-01-01
      • 2013-09-02
      相关资源
      最近更新 更多