简体   繁体   中英

friend function using template classes c++

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 .

1: What is the meaning of the term “free function” in C++?

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