error C2248 cannot access private member declared in class [duplicate]

耗尽温柔 提交于 2019-12-13 09:16:03

问题


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.



来源:https://stackoverflow.com/questions/30441287/error-c2248-cannot-access-private-member-declared-in-class

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