I made a class which has a friend function and when I declare it there are no problems but, when I write its code it returns me the error:
"Out-of-line definition of 'change' does not match any declaration in 'MyClass '".
Here's the code
template <class T>
class MyClass {
private:
T a;
public:
MyClass(T);
~MyClass();
friend void change(MyClass);
};
template <class T>
MyClass <T> :: MyClass(T value) {
a = value;
}
template <class T>
MyClass <T> :: ~MyClass() {}
template <class T>
void MyClass <T> :: change(MyClass class) { //Out-of-line definition of 'change' does not match any declaration in 'MyClass <T>'
a = class.a;
}
friend void change(MyClass);
does not declare a member function of MyClass
, it is an instruction for the compiler to grant the free function¹ void change(MyClass);
access to private/protected members of MyClass
.
The free function you grant access to MyClass
would then have to look that way:
template <class S>
void change(MyClass<S> obj) {
obj.a; // obj.a can be accessed by the free function
}
But the friend
then has to be declared that way in the class:
template <class T>
class MyClass {
private:
T a;
public:
MyClass(T);
~MyClass();
template <class S>
friend void change(MyClass<S>);
};
But based on a = class.a
in change
I think you actually want to have this:
template <class T>
class MyClass {
private:
T a;
public:
MyClass(T);
~MyClass();
void change(MyClass);
};
template <class T>
MyClass <T> :: MyClass(T value) {
a = value;
}
template <class T>
MyClass <T> :: ~MyClass() {}
template <class T>
void MyClass <T>::change(MyClass class) {
a = class.a;
}
A member function of MyClass
can always access all members of any instance of MyClass
.