c++ - 错误 : 'Friend Member Function Name' was not declared in this scope

标签 c++ linux oop codeblocks friend

我正在将我所有的 C++ Windows 应用程序迁移到 Ubuntu Linux。此应用程序在 Windows 7 操作系统的 Visual Studio 2015 Community 上运行良好。但是,在 Ubuntu Linux 上的代码块中运行时会出错。我已经使用以下简单的 Person 类复制了我收到的错误消息。

Error Message: 'comparePersonAge' was not declared in this scope

人.h

#ifndef Person_h
#define Person_h

#include <string>

class Person
{
private:
    int age;
    std::string name;
public:
    Person(int a, std::string n) : age(a), name(n) {}

    int getAge()
    {
        return age;
    }
    std::string getName()
    {
        return name;
    }
    inline friend bool comparePersonAge(const Person& p1, const Person& p2)
    {
        return p1.age < p2.age;
    }
};

#endif

main.cpp

#include <iostream>
#include <algorithm>
#include <vector>
#include "Person.h"

int main()
{
    Person p1(93, "harold");
    Person p2(32, "james");
    Person p3(67, "tracey");

    std::vector<Person> v;
    v.push_back(p1);
    v.push_back(p2);
    v.push_back(p3);

    std::sort(v.begin(), v.end(), comparePersonAge);

    std::cout << v[0].getAge() << " " << v[1].getAge() << " " << v[2].getAge()  << std::endl;
}

在 Windows 机器上,输出为:32 67 93,如预期的那样。在 Linux 上,错误消息如上所写。

注意:其他名为 DJR 的人在这篇文章中讨论了这个问题:Friend function not declared in this scope error . 然而,他的解释非常含糊,我没有按照他的步骤去做。

他写道:

Previous comment should have read: It is a bug on the the Linux side. The code should work as written. I have code right now that compiles fine on the Windows side and when I move it to the Linux side I get the same error. Apparently the compiler that you are using on the Linux side does not see/use the friend declaration in the header file and hence gives this error. By simply moving the friend function's definition/implementation in the C++ file BEFORE that function's usage (e.g.: as might be used in function callback assignment), this resolved my issue and should resolve yours also.

我不知道他把友元函数的定义移到函数使用之前的C++文件中是什么意思。这到底是什么意思?

最佳答案

friend 关键字的目的是对访问规则(protectedprivate)进行异常(exception)处理,给一个类或函数不允许访问成员。

因此,您可以在类声明之外声明和定义comparePersonAge() 函数,并在声明内使用friend 关键字,使该函数能够访问私有(private)成员,特别是年龄

关于c++ - 错误 : 'Friend Member Function Name' was not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463169/

相关文章:

linux - 一次删除 100 个文件并统计文件总数

java - 对象可以有访问修饰符吗?

c++ - 检查传递给方法的对象是否为 "this"

c++ - 在模板中使用#define VALUE

c++ - 如何将参数传递给 `_T()` ?

c++ - 一个定义规则和两个翻译单元中的不同类定义

linux - outb() 在 LDD3 示例短模块中不起作用

linux - 将 GIT 与 Jenkins 集成

c# - 每个算法具有不同方法签名的策略模式

javascript - 如何设置接收器