编译器对C++类提前声明的处理

本文介绍了C++编程中类的声明和使用规则,强调了在类未完全定义前只能声明对象而不能定义或访问其成员。通过示例代码展示编译错误,解释了编译器的工作原理,强调理解这些机制对于编写稳定高效代码的重要性,特别是处理类之间的相互引用时。

        在一般情况下,类必须先声明,然后,才能使用它。但是,在特殊的情况下(例如上面的例子),在正式声明定义类之前,需要使用该类名。但是,提前声明的使用范围是有限的,提前声明的时候,只能使用它去声明一个对象,例如,声明一个参数,但是,不能够调用它去定义一个对象。因为,这个类还没有编译,还不知道它有什么成员变量,所以,还不能够使用它去定义对象。如下是一个测试的例子:

       程序编译运行结果如下:

g++ test.cpp -o exe

wkf@ubuntu:~/c++$ ./exe

调用print()函数

       程序编译OK,可以正常运行。因为,在print()函数中,只是定义了student类的引用,并没有实际定义对象。

       那么,我们修改print()函数如下:

//定义函数引用 student ;

void print(student& s)

{

    cout << "调用print()函数" << endl;

    //定义student类对象

    student stud("wkf", "www.mylinux.vip", 13926572996);

}

       程序编译异常,异常信息如下:

wkf@ubuntu:~/c++$ g++ test.cpp -o exe

test.cpp: In function ‘void print(student&)’:

test.cpp:12: error: variable ‘student stud’ has initializer but incomplete type

       异常信息描述在print()函数中,定义的stud对象并不是合法的student类。因为,此时,编译器还没有编译student类,并不知道student类的具体定义,所以,无法使用student类来定义对象。

       同样的道理,编译器还没有执行student类的编译时,无法知道student类的具体定义,所以,就不可以使用student类来定义对象。同时,也不可以访问student类中的成员。所以,我们把print()函数放在student类定义之前。程序测试代码如下:

       编译运行结果如下:

wkf@ubuntu:~/c++$ g++ test.cpp -o exe

test.cpp: In function ‘void print(student&)’:

test.cpp:11: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

test.cpp:12: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

test.cpp:13: error: invalid use of incomplete type ‘struct student’

test.cpp:6: error: forward declaration of ‘struct student’

       可以看到,在print()函数中引用student对象的成员变量,是非法的操作。

       那么,根据这个思路,我们可以把print()函数放在student类定义来后面,就可以正确引用student类的成员了。测试代码如下:

    程序运行结果如下:

       可以看到,在student类定义的后面,在定义print()函数。那么,在print()函数中就可以访问student类的成员变量。

       所以,充分理解这个机制,理解编译系统的工作过程,在编写代码的时候,就可以合理地设计代码,当编译C++代码,有编译错误的时候,可以知道怎么样解决。

       特别是在设计模式中,多个类对象之间相互引用,此时,需要充分理解C++语言的特性,才可以根据设计模式的思想,编写出稳定、高效的代码。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

韦凯峰Linux编程学堂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值