【问题标题】:error C2248 cannot access private member declared in class [duplicate]错误 C2248 无法访问在类中声明的私有成员 [重复]
【发布时间】:2015-05-25 15:09:58
【问题描述】:

我们有一个 C++ 练习。老师在“课堂作业”的公共部分给了我们函数(所以我不能更改 header.h 中函数的公共声明)。当我尝试创建一个朋友 cout 函数时出现编译错误:编译器说“错误 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;
}

再次,我无法更改课程的公共部分。谢谢!

【问题讨论】:

  • 你的问题是什么?
  • 为什么我无法访问私人会员。我将该函数声明为友元函数
  • @jhkhjkhjkjhhj:正如在副本中解释的那样,您已将朋友声明在namespace biumath 中,然后在全局命名空间中定义了不同的函数。

标签: c++ visual-studio-2010 class friend-function


【解决方案1】:

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

【讨论】:

  • 正如我所说,我无法更改班级公共部分的声明。我可以进入私人部分,因为该功能是一个朋友功能。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 2012-11-15
    • 2016-12-02
    • 2013-07-28
    • 2011-09-06
    • 2015-03-25
    • 1970-01-01
    相关资源
    最近更新 更多