C++语言入门(一)从C过渡到C++

输出hello world

#include <iostream>
using namespace std;
int main(){
    cout<< "Hello world" <<endl; 
}
  1. 头文件#include <iostream>
  2. 命名空间 (名称空间)using namespace std;
  3. 标准输出流cout、输出运算符<<、换行控制器endl

一.源文件后缀

1.头文件后缀名:.hpp  .h

2.源文件后缀名:.cpp .cc .cxx 

二.引用头文件 

C++头文件使用C标准库,在C标准库文件名前加上字母c,并且省略后缀名.h

例如:

#include <stdlib.h>(C)#include <cstdlib>(C++)
#include <stdio.h>(C)            #include <iosteam> /#include <cstdio>(C++)

三.函数重载 

 函数重载:函数名相同,只有参数(个数或者类型)不相同。

例:实现一个打印函数,既可以打印int型、也可以打印字符串型。在C++中,我们可以这样做: 

#include<iostream>
using namespace std;

void print(int i)
{
        cout<<"print a integer :"<<i<<endl;
}

void print(string str)
{
        cout<<"print a string :"<<str<<endl;
}

int main()
{
        print(12);
        print("hello world!");
return 0;
}

通过上面代码的实现,可以根据具体的print()的参数去调用print(int)还是print(string)。上面print(12)会去调用print(int),print("hello world")会去调用print(string) 。

如在C中,你必须要这样去做:为这个print函数取不同的名字,如print_int、print_string。

所以,C不支持重载,C++支持重载。

四.名称空间 

       当可能使用两个已封装好的产品,而他们都包含一个名为wanda()的函数。这样使用wanda()函数时,编译器将不知道指的是哪个版本。名称空间让厂商能够将其产品封装在一个叫做名称空间的单元中,这样就可以用名称空间的名称来指出想使用哪个厂商的产品。

Microflop::wanda("go dancing?");       //use Microflop namespace version
Piscine::wanda("a fish named Desire"); //use Piscine namespace version

      类,函数和变量是C++编译器的标准组件,都被放置在名称空间std中。仅当头文件没有拓展名h时,情况才是如此。这意味着iostream中定义的用于输出的cout变量实际上是std::out。

   但有人不愿转换为名称空间代码,所以using编译指令出现:

using namespace std;

使得std名称空间中的所有名称都可用,而不必使用std::前缀。

只使所需的名称可用,可以通过using声明来实现:

using std::cout; //make cout available

C++命名空间处理方式

#include <cstdio>
namespace scope1 {
    void test(){
        printf("this is test\n");
    }
}
namespace scope2 {
    void test(){
        printf("this is another test\n");
    }
}
int main(){
    scope1::test();
    scope2::test();
}

.h后缀的头文件所包含和定义的标识符在全局命名空间中,不需要声明使用std空间

五.类型bool--true/false 

可以使用bool类型来表示真假,它们分别用预定义的字面值true和false,可以这样编写: 

 bool is_ready = true;

字面值true和false都可以通过提升转换为int类型,true被转换为1,而false被转换为0。 

int ans = true; //ans assigned 1

int promise = false; //ans assigned 0

另外,任何数字值或指针值都可以被隐式转换(即不用显示强制转换)为bool值。任何非零值都被转换为true,而零被转换为false。 

bool start = -100;  // start assigned true 

bool stop = 0;  // stop assigned false

六.动态内存 

#include <iostream>
using namespace std;
int main(){
      int* p = new int; //申请动态内存(new)
      *p = 100;
      std::cout << *p << std::endl;
      delete p;  //销毁内存
      p = NULL;

      int* q = (int*)malloc(sizeof(int));//申请动态内存(malloc)
      free(q); //销毁内存
      q = NULL;
}

七.初始化

int m(10);  // int m = 10; 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值