Reputation: 117
#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?
Upvotes: 2
Views: 13477
Reputation: 1011
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);
}
Upvotes: 1
Reputation:
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);
}
Upvotes: 0
Reputation: 234875
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
.
Upvotes: 6