前向声明类时成员函数的行为

时间:2018-04-26 23:57:02

标签: c++ class c++11 forward-declaration

当使用C ++ 11编译以下代码时,它的行为符合预期。

class Student;

class University
{
    vector <Student*> students;
public:
    University();
    void print();
};

class Student
{
    string name;
public:
    Student(string nom) : name(nom) {}
    friend ostream& operator << (ostream& out, Student* S)
    {
        return out << S -> name;
    }
};

University::University()
{
    for (string name: {"Alice", "Bob"})
        students.push_back(new Student(name));
}

void University::print() { for (auto s: students) cout << s << '\n'; }

int main()
{
    University uni;
    uni.print();
}

打印输出

Alice
Bob

但是,当print()函数在其类声明中实现时,如下所示:

class University
{
    vector <Student*> students;
public:
    University();
    void print() { for (auto s: students) cout << s << '\n'; }
};

打印输出

0x20055ff0
0x20056028

问题:为什么print()函数的行为与此类似,即使在第一行声明了Student

解决方案:在实现任何成员函数之前声明所有类。只要print()operator <<都在他们的课程之后实施,声明print()即使在operator <<

之前实施,也会正常运作

1 个答案:

答案 0 :(得分:6)

使用operator<<打印指针的默认行为是打印指向的内存地址的十六进制表示。

print()的实现在类声明中时,编译器还没有看到operator<<覆盖Student*指针,所以它不知道它应该表现如何与默认值不同。

print()覆盖之后定义operator<<实现时,编译器知道使用该覆盖而不是默认。