简体   繁体   中英

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?

DisplayAge in Utility is not a static function. Therefore you need an instance of Uitility in order to call it.

So, either make the function static , or call it via an anonymous temporary

Utility().DisplayAge(FirstMan);

Better still, make DisplayAge a member function of Human .

Use the static keyword and then you'll be able to call your function on your class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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