简体   繁体   English

没有对象就无法调用成员函数,但是我有一个对象才能调用该函数

[英]Cannot call member function without object but I call the function with an object

#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);
}

I don't understand..when I call the function I do send an object(FistMan)..why my compiler still says that I call it without object? 我不明白..当我调用函数时,我确实发送了一个对象(FistMan)..为什么我的编译器仍然说我在没有对象的情况下调用它?

DisplayAge in Utility is not a static function. Utility DisplayAge 不是 static函数。 Therefore you need an instance of Uitility in order to call it. 因此,您需要一个Uitility 实例才能调用它。

So, either make the function static , or call it via an anonymous temporary 因此,请将函数static ,或通过匿名临时函数调用它

Utility().DisplayAge(FirstMan);

Better still, make DisplayAge a member function of Human . 更妙的是,使DisplayAge成为Human的成员函数。

Use the static keyword and then you'll be able to call your function on your class 使用static关键字,然后就可以在类上调用函数

I edited your code below : 我在下面编辑了您的代码:

#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
{
friend class Human;
public:
    Utility() = default;
    static void DisplayAge(const Human& Person)
    {
        cout<<Person.Age<<endl;
    }
};

int main(void)
{
    Human FirstMan("Adam",25);
    cout<<"Accessing private member Age via friend class: ";
    Utility::DisplayAge(FirstMan);
}

Dön't use a class whenever you want to define functions. 只要要定义函数,就不要使用类。 Use a namespace: 使用名称空间:

namespace Utility
{
    inline 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM