在下面的代码中,如果我创建了College
类的University
类朋友,那么我就能够访问University
类的私有属性。但在College
类中,我只希望print函数访问这些私有属性。所以,我只将print
类的College
函数作为朋友,但这似乎并不起作用。我错过了什么或做错了什么?
错误:无法访问University
类的名称私有属性。
#include <iostream>
//class college;
class University{
//friend class college; // Works fine
friend void College::print(University &ob); // doesn't work
public:
University() = default;
University(int i, char *n) : buildings{ i }, name{ n } {}
private:
int buildings;
char *name;
};
class College{
public:
void print(University &ob){
std::cout << "I am a part of " << ob.name; // <-----------
}
};
int main()
{
University first{ 2000, "Mit" };
College c;
c.print(first);
return 0;
}
答案 0 :(得分:5)
为了使用
friend void College::print(University &ob);
班级College
的定义必须可见。
class University;
class College{
public:
void print(University &ob);
};
class University{
//friend class college; // Works fine
friend void College::print(University &ob);
public:
University() = default;
University(int i, char *n) : buildings{ i }, name{ n } {}
private:
int buildings;
char *name;
};
void Collelge::print(University &ob){
std::cout << "I am a part of " << ob.name; // <-----------
}