为什么不能使用私有成员
头文件new.h程序:#ifndef _NEW_H_
#define _NEW_H_
#include<string>
using namespace std;
class CStudent
{
private:
string strName;
int chinese;
int math;
int English;
public:
CStudent(string a,int b,int c,int d);
friend ostream& operator<<(ostream& out,CStudent S);
~CStudent(){}
};
#endif;
然后是类的实现程序,里面用到了一个输出流的重载:
#include<iostream>
#include"new.h"
#include<string>
using namespace std;
CStudent:: CStudent(string a,int b,int c,int d)
{
strName=a;
chinese=b;
math=c;
English=d;
}
ostream& operator<<(ostream& out,CStudent S)
{
cout<<"("<<S.strName<<","<<S.chinese<<","<<S.math<<","<<S.English<<")"<<endl;
return out;
}
最后是主程序:
#include<iostream>
#include"new.h"
#include<string>
using namespace std;
int main()
{
CStudent student1("Hector",78,88,98);
cout<<student1;
cin.get();
return 0;
}
但结果出错显示是不能访问类的私有变量:
student.cpp
C:\Program Files\Microsoft Visual Studio\MyProjects\s1\student.cpp(14) : error C2248: 'strName' : cannot access private member declared in class 'CStudent'
c:\program files\microsoft visual studio\myprojects\s1\new.h(8) : see declaration of 'strName'
C:\Program Files\Microsoft Visual Studio\MyProjects\s1\student.cpp(14) : error C2248: 'chinese' : cannot access private member declared in class 'CStudent'
c:\program files\microsoft visual studio\myprojects\s1\new.h(9) : see declaration of 'chinese'
C:\Program Files\Microsoft Visual Studio\MyProjects\s1\student.cpp(14) : error C2248: 'math' : cannot access private member declared in class 'CStudent'
c:\program files\microsoft visual studio\myprojects\s1\new.h(10) : see declaration of 'math'
C:\Program Files\Microsoft Visual Studio\MyProjects\s1\student.cpp(14) : error C2248: 'English' : cannot access private member declared in class 'CStudent'
c:\program files\microsoft visual studio\myprojects\s1\new.h(11) : see declaration of 'English'
当我把类定义中的权限改为Public后就可以了,这是为什么啊?那个输出流函数我已经定义为友元函数了啊? 将friend ostream& operator<<(ostream& out,CStudent S);用
friend ostream& operator<<(ostream& out,const CStudent &S);
代替试试。注意C++文件中的定义也相应要改动。
页:
[1]