无法访问类中声明的私有成员

error C2248 cannot access private member declared in class

本文关键字:成员 声明 访问      更新时间:2023-10-16

我们用c++做了一个练习。老师在"class Assignment"的public部分给了我们函数(所以我不能改变header.h中函数的public声明)。当我试图使朋友计数函数时,我得到了一个编译错误:编译器说"错误4错误C2248: 'biumath::Assignment::m_rowsOfVarArray':无法访问在类'biumath::Assignment'中声明的私有成员"。我认为问题出在命名空间上。

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;
}

还是不能更改类的公共部分。谢谢!

您的错误信息解释了这个问题。属性m_rowsOfVarArray被声明为private,这意味着您不能在类之外对它进行读取或写入。要解决这个问题,您需要将其更改为public或编写一个访问器函数来检索值。

您必须编写或使用public方法才能更改变量。使用private可以避免对变量进行任何意外或未经授权的更改。所以,只有你的public方法能够正确地改变它。