【问题标题】:Overloading the input operator to determine what kind of derived class to make?重载输入运算符以确定要制作什么样的派生类?
【发布时间】:2013-11-26 23:04:35
【问题描述】:

我有一个名为 Animal.h 的基类

在那里,我有描述动物发出的噪音的纯虚方法,这些噪音被派生类(例如猫/狗)(在它们自己的头文件中)覆盖。

我有一个主类来调用函数并打印出与这些类相关的不同内容。

我正在尝试重载 Animal.h 类中的输入运算符,以让我读取输入并根据输入的内容创建 Animal 类。

例如(在我的主要):

Animal *a = (animal*) 0;
while (read_animal(cin, a) && a)
    cout << *a << ’\n’;

在我的 Animal.h 中:

friend istream &operator >>( istream &input, animal* &animal_type )
{
    string in;
    getline(input, in);

    if (in.find("Cat") != std::string::npos)
    {
        *animal_type = new Cat();
    }
    return input;
}

但智能感知告诉我:

错误 3 错误 C2061:语法错误:标识符“Cat”

有什么想法吗?

【问题讨论】:

  • 应该是animal_type = new Cat();,我看不出你是如何在这段代码中遇到语法错误的。
  • #includeCat.h 了吗?这个类是不是叫Cat,而不是cat
  • Pawel 暗示 C++ 区分大小写。动物和动物不是一回事。
  • 如果我去掉 *.也没有 Cat.h 不包括在内,但我认为它不需要?
  • 如果你正在使用它完全可以......

标签: c++ pointers operator-overloading overloading


【解决方案1】:

原来的问题:

错误 3 错误 C2061:语法错误:标识符“Cat”

您的编译器不知道 Cat 是什么。
是否包含了相应的头文件。

但我不会那样做。

您的操作依赖于指针。这意味着您在没有所有权语义的情况下传递指针。这会导致各种各样的问题。如果您需要动态创建不同的类型,我将拥有一个知道如何创建特定类的不同类型的管理类型。

我会创建一个工厂(这描述了上面的关系(但还有其他技术)),它首先读取类型。然后创建一个合适的对象并用流初始化它。

class AnimalFactory
{
    public:
        static std::unique_ptr<Animal> deserializeAnimal(std::istream& str)
        {
              // 1 Detect the correct animal type.
              str ????

              // 2 Create the correct object.              
              std::unique_ptr<Animal>  result(new XXXX); // or constructor takes a stream?
                                     // how you decide XXXX depends a lot on other parts of
                                     // the system.

              // 3 use the input operator to initialize it.
              str >> (*result);      // unless you already did this with the constructor.

              return result;
        }
};

【讨论】:

    【解决方案2】:

    你有一个循环依赖。在定义Animal 的基类之前,您无法定义Cat 类,并且您对Animal::operator&gt;&gt; 的定义取决于Cat

    您需要将operator&gt;&gt; 分成两部分,头文件中的声明和包含正文的源。在源代码中,您可以包含定义 AnimalCat 的标头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-18
      • 2011-08-06
      • 2011-04-18
      • 1970-01-01
      • 2021-07-03
      • 1970-01-01
      相关资源
      最近更新 更多