本文介绍了错误:未在此范围内声明“朋友成员函数名称"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将所有C ++ Windows应用程序迁移到Ubuntu Linux.此应用程序可以在Windows 7 OS上的Visual Studio 2015社区上正常运行.但是,在Ubuntu Linux上的代码块中运行时,它会给出错误.我已经使用以下简单的Person类复制了错误消息.

I am in the process of moving all of my C++ Windows applications to Ubuntu Linux. This application runs fine on Visual Studio 2015 Community on Windows 7 OS. However, it gives an error when running in Code Blocks on Ubuntu Linux. I have replicated the error message I am getting using the following simple Person class.

Person.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上,错误消息如上所述.

On Windows machine, the output is: 32 67 93 as expected. On Linux, the error message is as written above.

注意:另一个人DJR在这篇文章中讨论了此问题:.但是,我对他的解释很含糊,不遵循他的步骤.

Note: Someone else name DJR discusses this issue in this post: Friend function not declared in this scope error.However, his explanation is very vague I and don't follow his steps.

他写道:

通过使用C ++文件中的朋友功能定义之前,我不知道他是什么意思.这到底是什么意思?

I don't know what he means by by moving the friend function's definition in the C++ file before the function's usage. What does this mean precisely?

推荐答案

标准7.3.1.2/3:

Standard 7.3.1.2/3 :

好了,在与@Niall进行少量讨论之后,我意识到MSVC ++在这种情况下是错误的,因为ADL仅出现在函数调用表达式中,并且由于std::sort仅传递了函数名,即comparePersonAge,没有函数comparePersonAge应该在调用std::sort时找到.因此,我认为GCC和Clang是正确的

Ok after little discussion with @Niall I realized that MSVC++ is wrong in this case, since ADL only happens in function call expression and since std::sort is being passed just name of function i.e comparePersonAge, no function comparePersonAge should be found at the time of call to std::sort . Hence GCC and Clang are correct I think

这篇关于错误:未在此范围内声明“朋友成员函数名称"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 18:25
查看更多