c++11标准风格

// c++11初始化风格
#include <iostream>
#include <string>

using namespace std;


int main()
{
    // c风格
    int num = 0;
    // c++风格
    int val(5);
    cout << "num = " << num << endl;
    cout << "val = " << val << endl;
    return 0;
}

// 1. c++11与c指针置空区别
// 2. c++11自动类型
// 3. decltype()
// 4. 在 C++11 及其之后的标准中,`decltype` 关键字用于推断表达式的类型,
//    我们可以用它来定义一些特殊的类型以及标准库中的一些元编程工具。
// 5. for
// 6. 给类型取别名
// 7. defaule在类中的用法
// 8. final
#include <iostream>
#include <string>
#include <type_traits>

using namespace std;

// 7. defaule在类中的用法
class MyClass
{
public:
    MyClass();
};
// 默认调用默认构造函数
MyClass::MyClass() = default; 

// 8. final
// final加在类后边,该类不能继承
class ClassA final
{
public:
    // final修饰的虚函数不能重写
    virtual void func() final {};
};

int main()
{
    // c++11与c指针置空区别
    int *ptr0 = NULL;
    int *ptr1 = nullptr;
    // 
    int num(0);
    // c风格指针赋值
    int *ptr2(&num);
    // c++风格指针赋值,自动匹配类型
    auto val(3);
    auto ptr3 = &val;
    cout << "val = " << val << endl;
    cout << "*ptr3 = " << *ptr3 << endl;

    // 在 C++ 中,`decltype` 关键字用于获取表达式的类型,但不实际执行该表达式。
    // 它可以用于以下场景:
    // decltype: 1. 获取变量或表达式的类型:
    int i = 42;
    decltype(i) j = i;  // j is an integer variable of the same type as i
    std::cout << "j = " << j << '\n';

    struct Foo { int mem; };
    const Foo foo{42};
    decltype(foo.mem) mem = foo.mem;  // mem is an integer variable of the same type as foo.mem
    std::cout << "mem = " << mem << '\n';

    std::conditional<sizeof(int) == 4, int, long>::type x;
    std::cout << "sizeof(x) = " << sizeof(x) << '\n';

    // c++新增的for特性
    string str("abcdefg");
    // c风格
    cout << "c风格: ";
    for (int i = 0; i < str.length(); i++) {
        cout << str[i] << " ";
    }
    cout << endl;
    // c++风格,成为序列for循环或范围for循环
    cout << "c++风格: ";
    for(auto ch : str) {
        cout << ch << " ";
    }
    cout << endl;

    // 6. 给类型取别名
    using Uint = int;
    Uint UintNum = 123;
    cout << "UintNum : " << UintNum << endl;
    
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值