gpt4 book ai didi

c++ - 没有对象不能调用成员函数,但我用对象调用函数

转载 作者:行者123 更新时间:2023-11-30 01:06:14 25 4
gpt4 key购买 nike

#include <iostream>
#include<string>
using namespace std;

class Human
{
private:
string Name;
int Age;
friend class Utility;
public:
Human(string InputName,int InputAge)
{
Name = InputName;
Age = InputAge;
}
};
class Utility
{
public:
void DisplayAge(const Human& Person)
{
cout<<Person.Age<<endl;
}
};
int main()
{
Human FirstMan("Adam",25);
cout<<"Accessing private member Age via friend class: ";
Utility::DisplayAge(FirstMan);
}

我不明白..当我调用函数时我确实发送了一个对象(FistMan)..为什么我的编译器仍然说我调用它时没有对象?

最佳答案

Utility 中的

DisplayAge 不是 static 函数。因此,您需要Utility实例 才能调用它。

因此,要么使函数静态,要么通过匿名临时调用它

Utility().DisplayAge(FirstMan);

更好的是,让 DisplayAge 成为 Human 的成员函数。

关于c++ - 没有对象不能调用成员函数,但我用对象调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46730859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com