【问题标题】:Factory Design and Inheritance工厂设计与继承
【发布时间】:2022-01-19 00:03:12
【问题描述】:

我正在为我的大学制作一个项目,在该项目中我正在实施工厂设计,但问题是我无法返回对象的地址,它给出了错误转换“不允许 C++ 转换为不可访问的基类”。

#include<iostream>

using namespace std;

class card
{
    protected:
       int fee;
       int limit;

    public:
       virtual void setvar() = 0;
};

class silver : card
{
    void setvar()
     {
        fee = 500;
        limit = 10000;
     }
};

class gold : card
{
    void setvar()
      {
         fee = 1000;
         limit = 20000;
      }
};

class platinum : card
{
    void setvar()
     {
        fee = 2000;
        limit = 40000;
     }
};

在这个类 FactoryDe​​sign 的返回行上给出了错误。

class factorydesign
{
    private :
        factorydesign();
    public:
        static card* getcard(int c)
         {
             if (c == 0)
              {
                return new silver();
              }
             else if (c == 1)
              {
                return new gold();
              }
             else if (c == 2)
              {
                return new platinum();
              }
         }

 };
 int main()
 {
      int choice;

      cout << "0 : Silver card\n1 : Golden Card\n2 : Platinum card \n";
      cin >> choice;

      card* obj;
      obj = factorydesign::getcard(choice);

      return 0;
 }

谁能详细解释一下为什么会这样?

【问题讨论】:

  • 您的card 类缺少虚拟析构函数,因此以多态方式使用是不安全的。

标签: c++ oop inheritance factory-pattern access-modifiers


【解决方案1】:

您需要公开继承它(class 默认为private

class silver : public card
{
  //...
};

你不能在外面访问私人基地,因为它是私人的(就像私人成员一样)

【讨论】:

  • 我没有访问派生类或基类的任何函数,我只是创建了派生类的新对象,我仍然必须公开继承它吗?你能解释一下我是编码新手吗:)
  • @MuhammadBilal 你把它作为基础返回。
【解决方案2】:

忽略问题中所有不相关的代码,问题是这样的:

class base {};
class derived : base {};

base *ptr = new derived;

derivedbase 继承私有,因此,正如错误消息所述,将new derived 创建的derived* 转换为base* 是不合法的。解决方法就是公开继承:

class derived : public base {};

【讨论】:

    猜你喜欢
    • 2020-10-25
    • 2014-05-03
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多