【问题标题】:Error: variable was not declared in this scope错误:未在此范围内声明变量
【发布时间】:2013-03-29 06:26:08
【问题描述】:

当我尝试编译下面的代码时,出现以下错误。

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;
}

ma​​in.cpp

#include<iostream.h>
#include<test1.h>
int main()
{
 display();
 return 0;
}

奇怪的是我能够在 unix 中成功编译。 我正在使用 gcc 和 g++ 编译器

【问题讨论】:

    标签: c++ c++builder


    【解决方案1】:

    您需要在将函数声明为好友之前提供该函数的声明。
    按照标准,作为朋友的声明不符合实际函数声明的条件。

    C++11 标准 §7.3.1.2 [namespace.memdef]:
    第 3 段:

    [...] 如果非本地类中的 friend 声明首先声明了一个类或函数,则友元类或函数是最内层封闭命名空间的成员。 在该命名空间范围内提供匹配声明之前,通过非限定查找或限定查找无法找到朋友的名称(在授予友谊的类定义之前或之后)。 [...]

    #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 
    };
    

    【讨论】:

      【解决方案2】:

      有趣。看起来 test1.hdisplay()friend 声明算作 g++ 中的实际函数声明。

      我认为标准实际上并未强制执行此操作,因此您可能希望在 test1.h 中为 display() 添加适当的声明:

      #include <iostream>
      
      int display();
      
      class Test
      {
      public:
          friend int display();
      };
      

      【讨论】:

      • 嗨,如果我们在类之外声明它,那么编译器会将这个函数视为普通函数而不是类 Test 的友元函数,并且将无法访问该类的成员变量.. 它会报错
      • @Akhirul,这不应该发生,除非您在添加正确的声明时删除了 friend 声明。
      • @AkhirulIslam:类外的函数声明告诉编译器存在一个同名的函数,它将接受这个参数,而类内的声明告诉编译器这个函数是这节课。两者无关,没有错误。你试过了吗?
      • 请检查我下面的代码:#include int display();类测试 { int a;公共:测试();朋友 int display(); }; #include #include "test1.h" using namespace std; int display() { cout
      • @Akhirul, friend 表示Test 的私有成员和受保护成员可以通过display() 访问,但您仍然需要将Test 的实例传递给display()让它访问其a 成员。 friend 函数不能凭空召唤成员。
      猜你喜欢
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-18
      • 2017-02-12
      • 1970-01-01
      相关资源
      最近更新 更多