This question already has an answer here:
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!
You have to write or use a
public
method in order to change your variable. You useprivate
to avoid any unexpected or unauthorised change of your variables. So, that only yourpublic
method is able to change it properly.Your error message explains the problem. The property
m_rowsOfVarArray
is declared asprivate
, which means you cannot read from it or write to it outside of the class. To fix this, you need to change it topublic
or write an accessor function to retrieve the value.