C++中的前向声明是什么

C++中的前向声明是什么

前向声明是指在使用(在程序的后面完成)之前预先声明标识符、变量、函数、类等语法或签名。
C++中的前向声明是什么
示例:

// sum()的前向声明
void sum(int, int);

// 使用sum()
void sum(int a, int b)
{
    // 函数主体
}

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

示例:

// 前向声明class A
class A;

// 定义class A
class A{
    // 类主体
};

前向声明的必要性:

让我们通过一个例子来了解前向声明的必要性。

例1。

// C++程序展示
// 前向声明的必要性
  
#include <iostream>
    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;
}  

输出:

编译错误:
prog.cpp:14:18: error: 'A' has not been declared
   friend int sum(A, B);
                  ^

解释:在这里,编译器会抛出错误,因为在B类中使用了A类的对象,在此之前没有声明。因此编译器无法找到类A。如果A类在B类之前编写,会怎样呢?让我们在下一个示例中找出答案。

示例2.

.
// C++程序展示
// 前向声明的必要性
  
#include <iostream>
    using namespace std;
  
class A {
public:
    int y;
  
    void getdata(int m)
    {
        y = m;
    }
    friend int sum(A, B);
};
  
class B {
  
public:
    int x;
  
    voidgetdata(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;
}  

输出:

编译错误:
prog.cpp:16:23: error: 'B' has not been declared
     friend int sum(A, B);
                       ^

解释:在这里,编译器会抛出错误,因为在A类中使用了B类的对象,在此之前没有声明。因此,编译器无法找到类B。

**现在很明显,无论类的顺序如何,上面的任何代码都不会起作用。因此,这个问题需要一个新的解决方案- **前向声明 。

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

示例3:

#include <iostream>
using namespace std;
  
// 前向声明
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

现在程序无错误运行。 A 前向声明 在实际定义一个实体之前告诉编译器该实体的存在。前向声明也可用于C++中的其他实体,例如函数、变量和用户定义类型。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程