0

我有两个类,它们都有许多扩展它们的类(用于多个级别)。由于多态性,我只在堆上分配它们。

我想重载<<operator,这样我就可以“流”到另一个。我想A << B简化为A->setNext(B),这个函数将 B 存储在一个数组中 - 所以我可以这样做五次并将所有 5 个都放在数组中。

我想在 2 个基类中为此编写代码,并让子类继承这些功能。这可能吗?


我想我找到了问题和解决方案:

我的 author.txt在将其转换为ANSI后被编码为UCS2 Little Endian,文件大小下降到 50% 并且可以正常工作。

文件大小从 70KB 下降到 35KB,但我不认为这是解决方案。

我的 author.txt 是使用 Windows Active Directory 中的 powershell 脚本创建的。

我还将行尾从CR LF更改为LF,但您提到,您也已经尝试过。所以我认为这是一个字符编码问题。

4

2 回答 2

0

在基类中,您需要以下内容:

class Base
{
    virtual void streamInto( Base const& other ) = 0;
public:
    Base& operator<<( Base const& other )
    {
        streamInto( other );
        return *this;
    }
};

当然,这仍然使语义保持开放:每个派生类如何处理Base const&它们收到的?如果 中的行为A也取决于 的类型other,那么您将不得不实现经典的双重调度方案之一。

真的<<适用于此吗?如果没有格式化为外部格式,则可能是运算符重载滥用。在诸如类之类的东西上转移BigInteger也是可以接受的,但仅此而已。

于 2013-06-24T16:30:02.733 回答
0

这可能是您正在寻找的东西。

// In B.hpp:
#include <memory>

class TypeB
  : public std::enable_shared_from_this<TypeB>
{
    //...
};

// In A.hpp:
#include <memory>
#include <vector>
#include "B.hpp"

class TypeA
{
public:
    TypeA& operator<<( TypeB& source );
    virtual void reset_B_list(); // (maybe)
    //...
private:
    typedef std::vector<std::shared_ptr<TypeB>> B_list_type;
protected:
    typedef B_list_type::const_iterator B_iter_type;
    B_iter_type B_list_begin() const;
    B_iter_type B_list_end() const;
    virtual void added_B( TypeB& new_source );
private:
    B_list_type m_B_list;
    //...
};

inline TypeA& TypeA::operator<<( TypeB& source ) {
    m_B_list.push_back( source.shared_from_this() );
    added_B( new_source );
    return *this;
}

请记住用 替换任何new B(args)表达式std::make_shared<B>(args)

如果你不能使用std::shared_ptr,几乎完全相同的东西在 Boost.

我同意詹姆斯的观点,这可能是对超载的滥用,这取决于这一切最终会做什么。考虑只使用一个普通的函数名,比如setNext,streamInto等。如果它返回TypeA&,你仍然可以“链”调用它,比如A.streamInto(B1).streamInto(B2);代替A << B1 << B2;

于 2013-06-24T16:54:18.720 回答