c++ compiler error cannot access private member declared in class 'std::basic_ios<_Elem,_Traits>'

对着背影说爱祢 提交于 2019-11-29 17:33:45

void PrintValues(const std::string& title, std::vector<std::vector<T>>& v, std::ofstream outfil) takes a std::ofstream by value, that is, copying the actual argument you pass to it, but fstreams may not be copied, hence the error you get regarding the private base it has.

You got it right when you thought of references as a solution, but you missed the point where you should use it. The correct way to solve your problem is to take a std::ofstream by reference in PrintValues, to do that, simply change its declaration to the following

Your guess is correct, `void PrintValues(const std::string& title, std::vector<std::vector<T>>& v, std::ofstream& outfil)

You need to understand what references are for first. A reference is like a permanent pointer to another variable that cannot be changed to refer to something else, and cannot be null. Since it can't be null, it makes no sense to declare a reference without saying what it refers to.

You can say

std::ofstream outfile_;
std::ofstream& outfil = outfile_;

if you're still interested in playing with references.

You are declaring outfil as a reference to an object of type std::ofstream with the following line in main:

std::ofstream & outfil;

References must be initialized upon declaration. Your solution is to declare outfil as:

std::ofstream outfil;

References must be initialized when they are created. There doesn't seem to be a use for references there anyway.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!