【发布时间】: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