简体   繁体   English

朋友 function 使用模板类 c++

[英]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:我做了一个 class ,它有一个朋友 function ,当我声明它时没有问题,但是当我编写它的代码时它返回错误:

"Out-of-line definition of 'change' does not match any declaration in 'MyClass '". “'change' 的离线定义与 '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);没有声明MyClass的成员 function ,这是编译器授予免费 function ¹ void change(MyClass); access to private/protected members of MyClass .访问MyClass的私有/受保护成员。

The free function you grant access to MyClass would then have to look that way:然后,您授予对MyClass访问权限的免费 function 必须是这样的:

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:但是必须在 class 中以这种方式声明friend

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:但是基于a = class.achange ,我认为你实际上想要这个:

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 . MyClass MyClass任何实例的所有成员。

1: What is the meaning of the term “free function” in C++? 1: C++中的“自由函数”是什么意思?

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

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