Friend function not declared in this error area

Hi, I’m trying to understand the scope of a friend’s functions, and I get an error “not declared in scope”. Here is my code:

//node.h class Node{ public: int id; int a; int b; friend int add(int,int); void itsMyLife(int); Node(); }; //node.cpp Node::Node(){ a=0; b=0; id=1; } void Node::itsMyLife(int x){ cout<<"In object "<<id<<" add gives "<<add(x,a)<<endl; } //routing.cpp #include "node.h" int add(int x, int y){ return x+y; } //main.cpp #include "node.h" int main(){ return 0; } 

I get the error "Add not declared in this area" in node.cpp. Why do I get this error when I declare a function in a class scope? Any help would be appreciated. Thanks

0
source share
3 answers

Inside the node class, you declare a friend function int add (int, int). However, the compiler has not yet come across this function, and therefore it is unknown.

You can create a separate header and source file for the add function. Then in node.h there is a new header. Since in the file where you are declaring node, the add function is not currently known.

So you can do add.h and the add.cpp file, for example, and add add.h before the node declaration. Remember to compile add.cpp as well.

+2
source

You have not actually declared this function.

 extern int add(int, int); 
0
source

His mistake is on the Linux side. The code should work. I have code right now that compiles on the Windows side, and when I switch to the Linux side, I get the same error. Apparently, the compiler that you use on the Linux side does not see / do not use the friend declaration in the header file and therefore gives this error. Just moving the implementation of the friend function to a C ++ file before using this function (for example, how you could use it when assigning a callback function), this fixed my problem and also solved your problem.

Best wishes

0
source

Source: https://habr.com/ru/post/1243244/


All Articles