Friend function not declared in this scope error

自闭症网瘾萝莉.ら 提交于 2019-12-12 04:58:00

问题


Hi I am trying to understand the scope of friend functions and I get a "not declared in scope" error. 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 scope" in node.cpp. Why do I get this error when I have declared the function in the class scope? Any help will be appreciated. Thanks


回答1:


Inside your node class you declare a friend function int add (int, int). However, currently the compiler hasn't encountered the function yet and therefore it is unknown.

You could make a separate header and source file for your add function. Then in node.h include you new header. Because in the file where you declare Node the function add is not known currently.

So you might make a add.h and a add.cpp file for example and include add.h before declaring Node. Don't forget to compile add.cpp as well.




回答2:


You haven't actually declared the function.

extern int add(int, int);



回答3:


Its a bug on the the Linux side. The code should work. I have code right now that compiles fine on the Windows side and when I move it to the Linux side I get the same error. Apparently the compiler that you are using on the Linux side does not see/use the friend declaration in the header file and hence gives this error. By simply moving the of the friend function's implementation in the C++ file BEFORE that function's usage (e.g.: as might be used in function callback assignment), this resolved my issue and should resolve yours also.

Best Regards



来源:https://stackoverflow.com/questions/16780013/friend-function-not-declared-in-this-scope-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!