繁体   English   中英

如何编写工厂方法; 我在遵循 C++ 代码时出错

[英]how to write a factory method; I have errors in following c++ code

我有一个 Shoe 基类。 这有一个静态方法 Create。 这将创建 2 个派生类对象 Shoe8 和 Shoe9。 setsize 和 getsize 方法是用于 Shoe 大小的 getter 和 setter 方法。 这里分别是 Shoe8 和 Shoe9 的 8 和 9。 但是我收到编译器错误。 如何摆脱它们?

  #include<stdio.h>
    #include<iostream>
    #include<vector>
    using namespace std;

    class Shoe
    {
        int size;
    public:
        static Shoe* Create(int num)
        {
            switch(num)
            {
                case 8:
                      return new Shoe8;
                case 9:
                      return new Shoe9;
            }
        }

        virtual void Detail() = 0;
        int getsize()
        {   
            return size;
        }
        void setsize(int sz)
        {   
            size = sz;
        }
    };


    class Shoe8:Shoe
    {
    public:
        Shoe8()
        {   
            setsize(8);
        }

        void Detail()
        {   
            cout<<"size = "<<getsize()<<endl;
        }
    };

    class Shoe9:Shoe
    {
    public:
        Shoe9()
        {   
            setsize(9);
        }

        void Detail()
        {   
            cout<<"size = "<<getsize()<<endl;
        }
    };

我得到的错误是

factory.cpp: In static member function ‘static Shoe* Shoe::Create(int)’:
factory.cpp:15:30: error: ‘Shoe8’ does not name a type; did you mean ‘Shoe’?
                   return new Shoe8;
                              ^~~~~
                              Shoe
factory.cpp:17:30: error: ‘Shoe9’ does not name a type; did you mean ‘Shoe’?
                   return new Shoe9;
                              ^~~~~

然后我尝试使用前向声明

class Shoe8;
class Shoe9;

我收到以下错误

factory.cpp: In static member function ‘static Shoe* Shoe::Create(int)’:
factory.cpp:19:30: error: invalid use of incomplete type ‘class Shoe8’
                   return new Shoe8;
                              ^~~~~
factory.cpp:7:7: note: forward declaration of ‘class Shoe8’
 class Shoe8;
       ^~~~~
factory.cpp:21:30: error: invalid use of incomplete type ‘class Shoe9’
                   return new Shoe9;
                              ^~~~~
factory.cpp:8:7: note: forward declaration of ‘class Shoe9’
 class Shoe9;

只需将方法声明和定义分开,因此当您定义/实现方法Create ,所有类定义都已经可用。

class Shoe
{
    int size;
  public:
    static Shoe* Create(int num);
    // Rest part of class
};

// Other classes go here

// After all classes are defined
Shoe* Shoe::Create(int num)
{
    switch(num)
    {
        case 8:
              return new Shoe8;
        case 9:
              return new Shoe9;
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM