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

后端 未结 4 2027
执笔经年
执笔经年 2020-12-22 11:38

Hey Im getting an error I think has to do with copying ofstream variable from reading other posts and Ive tried to change

std::ofstream outfil;
相关标签:
4条回答
  • 2020-12-22 11:57

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

    0 讨论(0)
  • 2020-12-22 11:59

    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)
    
    0 讨论(0)
  • 2020-12-22 11:59

    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;
    
    0 讨论(0)
  • 2020-12-22 12:20

    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.

    0 讨论(0)
提交回复
热议问题