error C2248 cannot access private member declared

2019-09-21 05:56发布

问题:

This question already has an answer here:

  • cannot access private members in friend ostream 3 answers

We got an exercise in c++. The teacher gave us the functions in the public part of the "class Assignment"(so I cannot change the public declaration of the functions in the header.h). I got an compilation error when i tried to make a friend cout function: the compiler say "Error 4 error C2248: 'biumath::Assignment::m_rowsOfVarArray' : cannot access private member declared in class 'biumath::Assignment'". I thinks that the problem is with the namespaces.

biumath.h

#ifndef BIUMATH_H
    #define BIUMATH_H
    #include <iostream>
    #include <string>
    //using namespace std;

    namespace biumath
    {
    class Assignment
    {
    private:
        int **m_varArray;
        int m_rowsOfVarArray;
    public:
         Assignment(); //1
         Assignment(char symbol, double value); //2
         bool containsValueFor(char symbol) const; //3
         double valueOf(char symbol) const; //4
         void add(char symbol, double val); //5
        friend std::ostream& operator<< (std::ostream& out,
            const Assignment& assignment); //6
        };
    }
    #endif

biumath.cpp

#include <iostream>
#include "biumath.h"
using namespace biumath;
using namespace std;
std::ostream& operator<< (std::ostream& out,
        const Assignment& assignment)
{
        out<<assignment.m_rowsOfVarArray<<std::endl;
        //return the stream. cout print the stream result.
        return out;
}

again I cannot change the public part of the class. thanks!

回答1:

Your error message explains the problem. The property m_rowsOfVarArray is declared as private, which means you cannot read from it or write to it outside of the class. To fix this, you need to change it to public or write an accessor function to retrieve the value.



回答2:

You have to write or use a public method in order to change your variable. You use private to avoid any unexpected or unauthorised change of your variables. So, that only your public method is able to change it properly.