C和C++之间的不同
(注,本文是翻译的http://www.cprogramming.com/
上的文章 Where C and C++ Differ
)
C++基于C,也保留了C的大部分特性。但是在源码级上有些地方是与C不兼容的。
C程序员使用C++时的陷阱
从 void* 的隐式分配
不能从 void* 隐式地分配到其他任何类型。例如,下面的代码在C中是非常有效的。
int *X = malloc(sizeof(int) * 10);
但是却不能在C++中编译。
按照Bjarne Stroustrup他自己的解释,这不是类型安全的。
考虑如下的代码:
int an_int;
void *void_pointer = &an_int;
double *double_ptr = void_pointer;
*double_ptr = 5;
当你给*double_ptr分配值5,其向内存中写入8个字节,但是整形变量an_int仅为4个字节。
程序应该注意这样的强制转换。
释放数组:new[] 和 delete[]
在C中,只有一种主要的内存分配函数:malloc 。你可以使用它来分配单一元素和数组:
int *X = malloc(sizeof(int);
int *x_array = malloc(sizeof(int) * 10);
你总是用相同的方法释放内存:
free(X);
free(x_array);
而在C++中,为数组的内存分配是不同于单一对象的,要使用 new[] 操作符,你还必须调用
delete[]来释放 new[] 分配的内存:
int *X = new int;
int *x_array = new int[10];
delete X;
delete[] x_array;
必须在使用函数前声明
虽然大部分的C代码都遵循这个约定,但是在C++中,使用函数前声明其是必须的。下面的代码
在C中是有效的,但是在C++中却无效:
#include <stdio.h>
int main()
{
foo();
return 0;
}
int foo()
{
printf("Hello world\n");
}
C++程序员使用C时的陷阱
结构体和枚举类型
声明一个结构体时,你必须在结构体类型的名字前加上 struct 关键字:在C++中,你可以这样:
struct a_struct
相关文档:
一、c++ 调C:
/* c语言头文件:cExample.h */
#ifndef C_EXAMPLE_H
#define C_EXAMPLE_H
#ifdef __cplusplus
extern "C"
{
#endif
int add(int x,int y);
#ifdef __cplusplus
}
#endif
#endif
/* c语言实现文件:cExample.c */
#include "cExample.h"
int add( int x, int y )
{
return ......
Windows C 程序设计入门与提高
http://download.chinaitlab.com/program/files/13246.html
单片机C语言入门
http://download.chinaitlab.com/program/files/12907.html
C++ 入门基础教程
http://download.chinaitlab.com/program/files/7617.html
C语言常用算法源代码
http://download.chinaitlab.com/program/files ......
一个控制台下的数字表达式求值程序 (c/c++)
源代码见下:
#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <stack>
using namespace std;
//设置运算符优先级的算法
int Priority(const string opera) // 运算符 ......
1 编程基础
1.1 基本概念
1. 的理解:const char*, char const*, char*const的区别问题几乎是C++面试中每次 都会有的题目。 事实上这个概念谁都有只是三种声明方式非常相似很容易记混。 Bja ......