📜  什么是C++中的Forward声明

📅  最后修改于: 2021-05-30 01:57:36             🧑  作者: Mango

转发声明是指在使用标识符之前先声明标识符,变量,函数,类等的语法或签名(在程序的后面进行)。

例子:

// Forward Declaration of the sum()
void sum(int, int);

// Usage of the sum
void sum(int a, int b)
{
    // Body
}

在C++中,正向声明通常用于类。在这种情况下,该类在使用之前就已预定义,以便可以由在此之前定义的其他类调用和使用。

例子:

// Forward Declaration class A
class A;

// Definition of class A
class A{
    // Body
};

需要前瞻性声明:

让我们通过一个示例来理解对前向声明的需求

范例1:

.
// C++ program to show
// the need for Forward Declaration
  
#include 
    using namespace std;
  
class B {
  
public:
    int x;
  
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
class A {
public:
    int y;
  
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
  
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}

输出:

Compile Errors :
prog.cpp:14:18: error: 'A' has not been declared
   friend int sum(A, B);
                  ^

说明:此处,编译器将引发此错误,因为在类B中,正在使用类A的对象,该对象在该行之前没有声明。因此,编译器找不到类A。那么,如果类A是在类B之前编写的,那该怎么办呢?让我们在下一个示例中查找。

范例2:

.
// C++ program to show
// the need for Forward Declaration
  
#include 
    using namespace std;
  
class A {
public:
    int y;
  
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
  
class B {
  
public:
    int x;
  
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}

输出:

Compile Errors :
prog.cpp:16:23: error: 'B' has not been declared
     friend int sum(A, B);
                       ^

说明:此处,编译器将引发此错误,因为在类A中,正在使用类B的对象,该对象在该行之前没有声明。因此,编译器找不到类B。

现在很明显,无论以何种顺序编写类,上述任何代码都将不起作用。因此,此问题需要一个新的解决方案-转发声明

让我们将前向声明添加到上面的示例中,然后再次检查输出。

范例3:

#include 
using namespace std;
  
// Forward declaration
class A;
class B;
  
class B {
    int x;
  
public:
    void getdata(int n)
    {
        x = n;
    }
    friend int sum(A, B);
};
  
class A {
    int y;
  
public:
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
int sum(A m, B n)
{
    int result;
    result = m.y + n.x;
    return result;
}
  
int main()
{
    B b;
    A a;
    a.getdata(5);
    b.getdata(4);
    cout << "The sum is : " << sum(a, b);
    return 0;
}
输出:
The sum is : 9

该程序现在运行没有任何错误。前向声明在实际定义实体之前将其存在告知编译器。前向声明也可以与C++中的其他实体一起使用,例如函数,变量和用户定义的类型。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”