美文网首页
Day1-C++初识

Day1-C++初识

作者: 秋风弄影 | 来源:发表于2017-07-01 23:13 被阅读0次

从Hello world开始

hello world.cpp

#include <iostream>
using namespace std;
int main(){
    cout<<"Hello world"<<endl; 
}

include <iostream>:表示的含义是IO流头文件;
using namespace std;:表示的含义是命名空间;
cout, cin表示的是命名空间里面的输出,输入对象,<<:表示的是输出运算符,>>:表示的是输入运算符号;

关于文件后缀

C语言的后缀通常是*.c,但是C++的后缀名通常是*.cpp*.cc*.cxx但是在Linux底下通常建议使用*.cpp

头文件的区别

C++头文件使用C标准库,通常是在C标准库的文件名前面加上c,但是需要省略.h;例如<cstdlib><cstring>

函数重载

函数重载表示的是在函数名相同,且只有参数(个数或者类型)不相同时;C语言是不支持重载的,但是C++是支持重载的;
关于重载的两个示例

  • printf.c
#include <stdio.h>
void printf(){
    printf("Hello world");
}
int main(){
    printf();
}
运行这个代码会出现: error: conflicting types for ‘printf’
也就是出现类型冲突;

*printf.cpp

#include <cstdio>
void printf(){
    printf("Hello world");
}
int main(){
    printf();
}
在这个过程中会出现函数重载的情况,printf(),
因为没有参数会执行定义的函数printf(),如果有参数就会执行系统函数;

命名空间

*test.c

#include <stdio.h>
void test(){
    printf("this is test\n");
}
void test(){
    printf("this is another test\n");
}
int main(){
    test();
}
会出现:error: redefinition of ‘test’;也就是出现函数名的重声明;

这个重声明的错误可以在C++中使用命名空间来解决;

  • 定义命名空间
namespace 空间名 {
}
  • 引用命名空间
using namespace 空间名;
  • 标准命名空间std
using namespace std;

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();
}

类型

*新增的类型是bool true/false

  • password.cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
      cout << "input user name:";
      char name[BUFSIZ];
      cin >> name;
      cout << "input 3 number password:";
      int password1;
      cin >> password1;
      cout << "input 3 number password again:";
      int password2;
      cin >> password2;
      cout << "password check:" << (password1 == password2) << endl;
}

*面向过程:强调的是如何处理;
*面向对象:强调的是执行处理的对象;

动态内存

  • dynamic_mem.c
#include <stdio.h>
#include <stdlib.h>
int main(){
      int* num = malloc(sizeof(int));
      *num = 100;
      printf("%d\n",*num);
      free(num); 
}
*C语言使用的是malloc和free来申请和释放内存;
  • dynamic_mem.cpp
#include <iostream>
int main(){
      int* num = new int;
      *num = 100;
      std::cout << *num << std::endl;
      delete num; 
}
*C++使用的是new和delete来申请和释放内存,并且不建议这两个函数进行混用;

*malloc 和free 虽然可以使用new和delete混合使用的,但是编译器处理的情况不同,所以是不建议混合使用的,并且new,delete做的操作要比malloc和free更多;所以需要注意的是malloc申请的内存,使用free释放时,需要将这个指针指为NULL;

相关文章

  • Day1-C++初识

    从Hello world开始 hello world.cpp include :表示的含义是IO流头文件;usi...

  • 初识flutter

    初识flutter 初识flutter

  • JS原型、原型链深入理解

    目录 原型介绍 初识原型 创建规则 初识Object 初识Function "prototype"和"_proto...

  • 初识四段戏

    一月初识最是干净 二月初识上了颜色 三月初识开始斑驳 四月初识便是褪去

  • HTML之初识HTML

    一、初识HTML 目录:初识HTML、网页基本信息、网页基本标签 1.初识HTML 1)什么是HTML?Hyper...

  • vue核心

    初识Vue 搭建基础框架 初识Vue