c++ - 重载运算符<<

标签 c++ c++11 operator-overloading

我想重载operator<<像这样:

ostringstream oss;
MyDate a(2000, 1, 2);
oss << dateFormat("%Y/%m/%d") << a;
assert(oss.str() == "2000-01-02");

这样日期就在 a将被格式化为特定格式。如何实现这一目标?

最佳答案

为了在流中存储自定义状态,您需要使用xalloc静态函数来获取唯一索引,然后使用pword来获取指向的指针该索引(专门为其使用的每个流分配)​​,或 iword 来获取该索引处的整数(专门为其使用的每个流分配)​​。就您而言,您可能需要pword。您可以使用pword返回的指针来指向存储格式信息的动态分配的对象。

struct DateFormatter
{
    // The implementation of this class (e.g. parsing the format string)
    // is a seperate issue. If you need help with it, you can ask another
    // question

    static int xalloc_index;
};

int DateFormatter::xalloc_index = std::ios_base::xalloc();

void destroy_date_formatter(std::ios_base::event evt, std::ios_base& io, int idx)
{
    if (evt == std::ios_base::erase_event) {
        void*& vp = io.pword(DateFormatter::xalloc_index);
        delete (DateFormatter*)(vp);
    }
}

DateFormatter& get_date_formatter(std::ios_base& io) {
    void*& vp = io.pword(DateFormatter::xalloc_index);
    if (!vp) {
        vp = new DateFormatter;
        io.register_callback(destroy_date_formatter, 0);
    }
    return *static_cast<DateFormatter*>(vp);
}

std::ostream& operator<<(std::ostream& os, const DateFormatter& df) {
    get_date_formatter(os) = df;
    return os;
}

std::ostream& operator<<(std::ostream& os, const MyDate& date)
{
    DateFormatter& df = get_date_formatter(os);

    // format output according to df

    return os;
}

int main() {
    MyDate a ( 2000, 1, 2 );
    std::cout << DateFormatter("%Y/%m/%d") << a;
}

这是标准方法。在我看来,这太可怕了。我更喜欢另一种方法,即将日期对象与格式一起作为单个对象传递。例如:

class DateFormatter
{
    const MyDate* date;
    std::string format_string;
    DateFormatter(const MyDate& _date, std::string _format_string)
        :date(&_date)
        ,format_string(_format_string)
    {}

    friend std::ostream& operator<<(std::ostream& os, const DateFormatter& df) {
        // handle formatting details here
        return os;
    }
};

int main() {
    MyDate a ( 2000, 1, 2 );
    std::cout << DateFormatter(a, "%Y/%m/%d");
}

关于c++ - 重载运算符<<,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671493/

相关文章:

c++ - SVM(支持 vector 机)opencv

c++ - numeric_limits<int>::is_modulo 在逻辑上是否矛盾?

c++ - 在 std::vector 中存储函数在 linux 上可以正常工作,但甚至不能在 windows 上编译

c++ - 通过指向数据成员的指针进行类成员访问是否被视为成员访问表达式?

c++ - 如何使用从 synaptic 安装的 FLANN

c++ - 检查模板参数是否属于类类型?

c++ - 将元素添加到 STL 容器的背面

c++ - 构造类的返回值

c++ - 抽象类(接口(interface))中的运算符重载

c++ - C++中后缀自增运算符中int变量的含义