sách gpt4 ăn đã đi

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

In lại 作者:IT王子 更新时间:2023-10-29 00:37:40 26 4
mua khóa gpt4 giày nike

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

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

人.h

#ifndef Person_h
#define Person_h

#include

lớp Người
{
riêng tư:
int age;
std::string name;
công cộng:
Person(int a, std::string n) : age(a), name(n) {}

int getAge()
{
tuổi trở về;
}
std::string getName()
{
trả về tên;
}
inline friend bool comparePersonAge(const Person& p1, const Person& p2)
{
return p1.age < p2.age;
}
};

#kết thúc nếu

main.cpp

#include 
#include
#include
#include "Person.h"

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

std::vector 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++文件中是什么意思。这到底是什么意思?

câu trả lời hay nhất

bạn bè 关键字的目的是对访问规则(được bảo vệriêng tư)进行异常(exception)处理,给一个类或函数不允许访问成员。

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

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

26 4 0
IT王子
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress