简体   繁体   English

函数中的默认ofstream类参数

[英]Default ofstream class argument in function

I've got function. 我有功能。 If user didn't provide ofstream element into this function: 如果用户没有在此函数中提供ofstream元素:

bool isPolpierwsza(int, bool = false, ofstream = NULL);

than I want to asign "plik" 比我想要“plik”

bool isPolpierwsza(int liczba, bool wypisz, ofstream plik)

to NULL value. NULL值。

My compiler put error: 我的编译器放错了:

2.9.cpp:5:48: error: no viable conversion from 'long' to 'ofstream' (aka 'basic_ofstream') 2.9.cpp:5:48:错误:没有可行的从'long'转换为'ofstream'(又名'basic_ofstream')
bool isPolpierwsza(int, bool = false, ofstream = NULL);

How to setup default value to ofstream to be treated like NULL or "false"? 如何设置ofstream的默认值被视为NULL或“false”?

You can use two overloads, one of which doesn't take the std::ofstream argument: 您可以使用两个重载,其中一个std::ofstream参数:

bool isPolpierwsza(int liczba, bool wypisz)
{
    return isPolpierwsza(liczba, wypisz, /* your own argument */);
}

You could pass the stream buffer instead: 您可以改为传递流缓冲区:

bool isPolpierwsza(int, bool = false, std::streambuf* osbuf = nullptr)
{
    std::ostream os(osbuf? osbuf : std::cout.rdbuf());
    os << "yay it works\n";
    return false;
}

Now, call it like this: 现在,这样称呼它:

std::ofstream ofs("myoutput.txt");
bool result = isPolpierwsza(42, true, ofs.rdbuf());

Or indeed, without the parameter. 或者确实没有参数。

First of all, it may be useful to use ostream instead of ofstream, as this is more general and considered better practice. 首先,使用ostream而不是ofstream可能是有用的,因为这是更通用的并且被认为是更好的实践。

Then, you can simply assign 'cout' instead of 'NULL'. 然后,您可以简单地指定'cout'而不是'NULL'。 NULL doesn't work because ostream is not a pointer but a struct. NULL不起作用,因为ostream不是指针而是结构。 This means the struct has to be filled out completely and can not be assigned NULL. 这意味着必须完全填写结构,并且不能将其指定为NULL。 Instead, you could use cout, like 相反,你可以使用cout,比如

bool isPolpierwsza(int, bool = false, ostream& = cout);

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

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