即使在成员函数成为朋友之后也无法访问成员

时间:2015-02-26 19:05:53

标签: c++

在下面的代码中,如果我创建了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; 
}

1 个答案:

答案 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;   // <-----------
}