c与c++差别翻译
- 格式:doc
- 大小:44.50 KB
- 文档页数:5
ISO C与ISO C++的差别
本文仅翻译主要内容
翻译:莫斌耀
日期:2011年11月24日
原文信息:
Incompatibilities Between ISO C and ISO C++
By David R. Tribble
david@
Revision 1.0, 2001-08-05
出处:/text/cdiffs.htm
C++中新增的概念
anonymous unions 匿名联合
classes 类
constructors and destructors 构造与析构
exceptions and try/catch blocks 异常处理与try/catch语句
external function linkages (e.g., extern "C")外部函数联系
function overloading 函数重载
member functions 成员函数
namespaces 命名空间
new and delete operators and functions new与delete运算符与功能
operator overloading 运算符重载
reference types 引用类型
standard template library (STL) 标准模板库(STL)
template classes 类模板
template functions 函数模板
从C++98到C99的变化
以下内容在C90和C++98中不兼容,但从C99开始兼容:
聚合类型初始化C90仅允许用常量初始化集合类型(数组、结构、联合),而在C99中取消了这一限制,例如:
// C and C++ code
void foo(int i)
{
float x = (float)i; // V alid C90, C99, and C++
int m[3] = { 1, 2, 3 }; // V alid C90, C99, and C++
int g[2] = { 0, i }; // Invalid C90
}
●注释C++要求用两个斜杠(//),C90只认识/*….*/这样的注释符号,而从C99开始,
这两种注释语法都被允许。
●C++允许在条件表达式(for,if,while,switch)中使用局部变量,例如:
for (int i = 0; i < SIZE; i++)
a[i] = i + 1;
C90 不允许这样的语法,C99允许,但仅限于for语句。
●双字符符号
C++/C99承认但C90不认可的双字符符号如下:
<: [
:> ]
<% {
%> }
%: #
%:%: ##
以下语法在C99 and C++中都有效:
%:include
%:ifndef BUFSIZE
%:define BUFSIZE 512
%:endif
void copy(char d<::>, const char s<::>, int len)
<%
while (len-- >= 0)
<%
d<:len:> = s<:len:>;
%>
%>
●隐藏函数声明
在C90中:
void foo(void)
{
bar(); /* 隐含声明: extern int bar() */
}
C++ 和C99不允许。
●C90只允许在语句块的开头声明变量与常量,C++/C99则无此限制:
void prefind(void)
{
int i;
for (i = 0; i < SZ; i++)
if (find(arr[i])) break;
const char * s; /* Invalid C90, valid C99 and C++ */
s = arr[i];
prepend(s);
}
C99与C++98的差别
●C++增加了一组关键字与右边的运算符等效:
and &&
and_eq &=
bitand &
bitor |
compl ~
not !
not_eq !=
or ||
or_eq |=
xor ^
xor_eq ^=
C99中虽然没有上面这些关键字,但是
●C99增加了关键字_bool,并在
而在C++中,bool、true、false是关键字。
●在C中,sizeof(‘a’)等效于sizeof(int);而在C++中,sizeof(‘a’)等效于sizeof(char)。在某
些时候,这个差别可能带来致命问题:
memset(&i, 'a', sizeof('a')); // Questionable code
●clog identifier
C99 declares clog() in
C++ declares std::clog in