Skip to Content
C++语言导学(原书第2版)
book

C++语言导学(原书第2版)

by 本贾尼 斯特劳斯特鲁普
August 2021
Intermediate to advanced
450 pages
5h 35m
Chinese
Pearson
Content preview from C++语言导学(原书第2版)

16.3.2 兼容性问题

C和C++有很多小的不兼容之处。所有这些不兼容都能给程序员带来麻烦,但也都可以在C++中解决。如果没有其他不可解决的不兼容问题,C代码片段可以作为C程序编译并使用extern"C"机制与C++程序链接到一起。

将一个C程序转换为C++程序可能遇到的主要问题有:

·次优的设计和编程风格。

·将一个void*隐式转换为一个T*(即,没有使用显式类型转换)。

·在C代码中将C++关键字用作了标识符,如class和private。

·作为C程序编译的代码片段和作为C++程序编译的代码片段链接时不兼容。

16.3.2.1 风格问题

C程序自然按C风格来编写,例如K&R风格[Kernighan,1988]。这意味着到处使用指针和数组,可能还有大量的宏。用这些设施编写大型程序,很难做到可靠。还有,资源管理和错误处理代码通常是为特定程序专门编写的,通过文档说明(而不是语言和工具所支持的),而且文档往往不完整,代码的依附性也太强。将一个C程序简单地逐行转换为一个C++程序,对得到的程序最好进行全面检查。实际上,我将C程序改写为C++程序从来没有无错的。这种改写工作,如果不改变基础结构,那么根本的错误来源也就仍然存在。如果原始的C程序中就有不完整的错误处理、资源泄漏或是缓存溢出,那么在C++版本中它们还会存在。为了获得大的收益,你必须改变代码的基础结构:

(1)不要将C++看作增加了一些特性的C。你可以这样来使用C++,但这将导致次最优的结果。为了真正发挥C++相对于C的优势,你需要采用不同的设计和实现风格。

(2)将C++标准库作为学习新技术和新程序设计风格的老师。注意它与C标准库的差异(例如,字符串拷贝用=而不是strcpy()以及字符串比较用==而不是strcmp())。 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

软件开发实践:项目驱动式的Java开发指南

软件开发实践:项目驱动式的Java开发指南

Raoul-Gabriel Urma, Richard Warburton
管理Kubernetes

管理Kubernetes

Brendan Burns, Craig Tracey
Python机器学习案例精解

Python机器学习案例精解

Posts & Telecom Press, Yuxi (Hayden) Liu

Publisher Resources

ISBN: 9787111633280