c – 错误:未在此范围内声明变量
作者:互联网
当我尝试编译下面的代码时,我收到以下错误.
Error: main.cpp: In function "int main()":
main.cpp:6: error: "display" was not declared in this scope
test1.h
#include<iostream.h>
class Test
{
public:
friend int display();
};
test1.cpp:
#include<iostream.h>
int display()
{
cout<<"Hello:In test.cc"<< endl;
return 0;
}
main.cpp中
#include<iostream.h>
#include<test1.h>
int main()
{
display();
return 0;
}
奇怪的是我能够成功地在unix中编译.
我正在使用gcc和g编译器
解决方法:
在将其声明为朋友之前,您需要提供该函数的声明.
作为朋友的声明不符合标准的实际功能声明.
C 11标准§7.3.1.2[namespace.memdef]:
第3段:
[…] If a
friend
declaration in a nonlocal class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by unqualified lookup or by qualified lookup until a matching declaration is provided in that namespace scope (either before or after the class definition granting friendship). […]
#include<iostream.h>
class Test
{
public:
friend int display(); <------------- Only a friend declaration not actual declaration
};
你需要:
#include<iostream.h>
int display(); <------- Actual declaration
class Test
{
public:
friend int display(); <------- Friend declaration
};
标签:c,cbuilder 来源: https://codeday.me/bug/20190901/1780528.html