Linux C/C++教程(二)-- C++对C的拓展

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/susidian/article/details/82591138

 

目录

 

一、bool类型关键字

二、引用

三、输入输出

四、函数参数

五、string类

六、左值


一、bool类型关键字

C++在C语言的基础类型上新增了布尔类型(bool),bool可取的值有两个:true、false,占用一个字节。true代表真值,编译器内部用1来表示;false代表非真值,编译器内部用0来表示。

#include <iostream>
using namespace std;

int main() {
    bool flag = true;
    std::cout << "bool[true] 值:" << flag << std::endl;
    std::cout << "bool占用字节数:" << sizeof(flag) << std::endl;
    flag = 10;
    std::cout << "修改bool[true]值后,值:" << flag << std::endl;
    
    return 0;
}

输出:

bool[true] 值:1
bool占用字节数:1
修改bool[true]值后,值:1

二、引用

在C++中才引入引用类型,它是变量的别名,声明方法:类型标识符 &引用名 = 目标变量名,表达式用的&不代表取变量的地址,而是用来表示该变量是引用类型的变量,定义一个引用时,一定要对其进行初始化。

#include <iostream>
using namespace std;

void func(int &arg) {
    arg = 14;
}

int main() {
    int a = 11;
    int c = 12;
    int &b = a;
    b = 13;
    std::cout << "a = " << a << ", b = " << b << std::endl;
    std::cout << "before func c = " << c << std::endl;
    func(c);
    std::cout << "after func c = " << c << std::endl;

    return 0;
}

输出:

a = 13, b = 13
before func c = 12
after func c = 14

三、输入输出

C语言中输入输出是标准的函数scanf()和printf(),而C++中使用流对象作为输入输出,其中cin是标准输入流对象,即istream类的对象;cout是标准输出流的对象,即ostream类的对象;cerr是标准错误输出流的对象,也是ostream 类的对象。

四、函数参数

C语言中,函数定义时没有给定参数或返回类型,默认使用int类型,如:int func()表示接收任意参数的函数;func()表示返回值int的函数。但C++中,所有的标识符必须显示声明类型,否则无法通过编译;其次C++允许函数设置参数默认值。

#include <stdio.h>

int func1() {
    return 1;
}

func2(void) {
    return 2;
}

int main() {
    int func1_ret = func1(23, 43);
    printf("func1 return[%d]\n", func1_ret);
    int func2_ret = func2();
    printf("func2 return[%d]\n", func2_ret);

    return 0;
}

输出:

func1 return[1]
func2 return[2]

#include <iostream>
using namespace std;

int func1() {

    return 1;
}

int func2(int a, int b = 2) {
    std::cout << "a = " << a << ", b = " << b;

    return 0;
}

int main() {
    int a = 1;
    int b = 3;
    std::cout << "func1 return[" << func1() << "]" << std::endl;
    std::cout << "func2 use default param ";
    int ret1 = func2(a);
    std::cout << std::endl;
    std::cout << "func2 use set param ";
    int ret2 = func2(a, b);
    std::cout << std::endl;

    return 0;
}

输出:

func1 return[1]
func2 use default param a = 1, b = 2
func2 use set param a = 1, b = 3

五、string类

C语言是静态弱类型语言,类型在编译时需要确定,对于string类型,由于它的大小无法在编译时确定,所以C语言中没有string类型,通过char *和char []可以定义字符串。C++中的string类是一个模板类,位于std命名空间中,使用string类,头文件必须包含<string>。

#include <iostream>
#include <string>
using namespace std;

int main() {
    std::string mystr("abc");
    std::cout << "mystr:" << mystr << ", size:" << mystr.size() << std::endl;

    return 0;
}

输出:

mystr:abc, size:3

六、左值

左值一定可以作为右值,但右值不一定可以作为左值,C语言中表达式不能作为左值,而C++中只要能建立普通引用的表达式都可以作为左值。

a > b ? a : b = 10; // 三目运算符返回变量本身,可以作左值

猜你喜欢

转载自blog.csdn.net/susidian/article/details/82591138