简体   繁体   English

C ++函数重载,使fwrite / fread的行为类似于PHP版本

[英]c++ function overloading, making fwrite/fread act like PHP versions

I'm used to the PHP fwrite/fread parameter orders, and i want to make them the same in C++ too. 我习惯了PHP fwrite / fread参数的顺序,并且我也想使它们在C ++中相同。

I want it to work with char and string types, and also any data type i put in it (only if length is defined). 我希望它可以处理char和string类型,以及我放入的任何数据类型(仅在定义了长度的情况下)。

I am total noob on c++, this is what i made so far: Edit: fixed the std::string &buf 我对C ++完全陌生,这是我到目前为止所做的: 编辑:修复了std :: string&buf

size_t fwrite(FILE *fp, const std::string &buf, const size_t len = SIZE_MAX){
    if(len == SIZE_MAX){
        return fwrite(buf.c_str(), 1, buf.length(), fp);
    }else{
        return fwrite(buf.c_str(), 1, len, fp);
    }
}

size_t fwrite(FILE *fp, const void *buf, const size_t len = SIZE_MAX){
    if(len == SIZE_MAX){
        return fwrite((const char *)buf, 1, strlen((const char *)buf), fp);
    }else{
        return fwrite(buf, 1, len, fp);
    }
}

Should this work just fine? 这个工作应该很好吗? And how should this be done if i wanted to do it the absolutely best possible way? 如果我想以绝对最佳的方式做到这一点,该怎么办?

If you want to write to a file in the best possible way, you should use std::iostreams. 如果要以最佳方式写入文件,则应使用std :: iostreams。 Dealing with the length of the buffer manually is a recipe for problems. 手动处理缓冲区的长度是解决问题的方法。

Also, the top overload should take a const std::string&, not const std::string. 另外,顶部重载应采用const std :: string&,而不是const std :: string。

However, I don't see any actual bugs. 但是,我看不到任何实际的错误。

fwrite / fread don't really work very well with objects; fwrite / fread在对象上不能很好地工作; so as @DeadMG says you'd be better of with streams. 因此,如@DeadMG所说,最好使用流。

something like: 就像是:

cout << str << endl;

It's a much more OO way of doing things - you can overload the operators within the objects to handle the different requirements of each individual object. 这是一种更加面向对象的处理方式-您可以使对象内的运算符超载,以处理每个单个对象的不同要求。

This isn't the right sort of overloading of functions IMO. 这不是IMO函数的正确重载。 If anything these functions should be methods within the object. 如果有的话,这些函数应该是对象内的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM