如何向标准库中的类添加新方法

问题描述 投票:0回答:1

我想从

std::fstream
标头扩展
<fstream>
类。我计划添加一些功能,例如
std::fsteam create(path)
std::vector<std::string> read_lines(path)
等。

我问的很简单。我希望能够简单地在另一个文件中添加方法,然后创建

std::fstream
对象并使用这些新方法,而不是创建一个全新的类。

我有两个文件。

file_helper.hh
我将在其中声明方法,以及
file_helper.cc
我将在其中定义它们并将它们链接到我的
main.cc
文件。

那么,如果可能的话,我应该在

file_helper.hh
中编写什么来将这些新方法添加到
std::fstream
中?还可能吗?

c++ fstream
1个回答
0
投票

在 C++ 中执行此操作的方法是添加您自己的独立函数以及您想要的功能:

// stdex.h
#include <fstream>

namespace stdex 
{
    std::vector<std::string> read_lines(std::ifstream& self);
}

然后你就可以像使用任何函数一样使用它们:

// main.cpp
#include <fstream>
#include <iostream>

#include "stdex.h"

int main()
{
    std::fstream file{"foobar.txt"};
    for (const auto& line : stdex::read_lines(file)) {
        std::cout << line << '\n';
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.