[C++] 用Xcode来写C++程序[2] 操作变量

简介:

用Xcode来写C++程序[2] 操作变量

 

此节讲解包括变量的初始化的几种方式,以及泛型编程的两种变量赋值方式.

 

最基本的变量赋值以及操作:

// operating with variables

#include <iostream>
using namespace std;

int main ()
{
    // 声明变量
    int a, b;
    int result;
    
    // 赋值
    a = 5;
    b = 2;
    a = a + 1;
    result = a - b;
    
    // 打印结果
    cout << result;
    
    return 0;
}

带有构造器的初始化方式:
// initialization of variables

#include <iostream>
using namespace std;

int main ()
{
    int a = 5;   // 普通初始化
    int b(3);    // constructor initialization 构造器初始化
    int c{2};    // uniform initialization     联合初始化 (2011的C++版本中被提出来)
    int result;  // 定义没有赋值的变量
    
    a = a + b;
    result = a - c;
    cout << result << endl;
    
    return 0;
}

类型推演赋值:
// initialization of variables

#include <iostream>
using namespace std;

int main ()
{
    /**
     *  类型推演 (会降低程序可读性)
     *
     *  auto
     *  decltype
     *
     */
    
    // auto
    int foo  = 7;
    auto bar = foo;  // bar与foo类型一致,并且赋了值,其值为7
    cout << bar << endl;
    
    // decltype
    decltype(foo) cat; // cat与foo类型一致,不过没有赋值
    cout << cat << endl;
    
    return 0;
}

打印:

7

0

Program ended with exit code: 0

操作字符串:(注意,需要引入头文件string)

// my first string
#include <iostream>
#include <string>

using namespace std;

int main ()
{
    // 定义字符串
    string mystring;
    
    // 字符串赋值
    mystring = "This is a string";
    
    // 输出字符串
    cout << mystring << endl;
    
    return 0;
}

当然,你也可以用以下的几种方式初始化字符串:

string mystring = "This is a string";  // 常规模式
string mystring ("This is a string");  // 构造器模式
string mystring {"This is a string"};  // 联合初始化模式

目录
相关文章
|
28天前
|
存储 缓存 算法
【C/C++ 性能优化】提高C++程序的缓存命中率以优化性能
【C/C++ 性能优化】提高C++程序的缓存命中率以优化性能
113 0
|
30天前
|
存储 C++ 容器
学会在 C++ 中使用变量:从定义到实践
C++中的变量是数据容器,包括`int`、`double`、`char`、`string`和`bool`等类型。声明变量时指定类型和名称,如`int myNum = 15;`。`cout`与`&lt;&lt;`用于显示变量值。常量用`const`声明,值不可变。变量名应唯一,遵循特定命名规则,常量声明时需立即赋值。
113 1
|
1月前
|
编译器 C++
C++ 双冒号::开头的语法,::变量名,获取全局作用域变量
C++ 双冒号::开头的语法,::变量名,获取全局作用域变量
17 0
|
1月前
|
存储 C++
C++系列三:变量、常量
C++系列三:变量、常量
|
16天前
|
人工智能 机器人 C++
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
【C++/Python】Windows用Swig实现C++调用Python(史上最简单详细,80岁看了都会操作)
|
30天前
|
存储 JSON 安全
【C++ JSON库 json值的创建手段】深入探究C++中JSON对象定位与操作:从引用到回调函数
【C++ JSON库 json值的创建手段】深入探究C++中JSON对象定位与操作:从引用到回调函数
62 0
|
16天前
|
存储 程序员 编译器
C++注释、变量、常量、关键字、标识符、输入输出
C++注释、变量、常量、关键字、标识符、输入输出
|
23天前
|
C语言 C++
C/C++文件读取操作
C/C++文件读取操作
|
23天前
|
存储 缓存 C++
C++链表常用的函数编写(增查删改)内附完整程序
C++链表常用的函数编写(增查删改)内附完整程序
|
28天前
|
存储 算法 数据管理
C++中利用随机策略优化二叉树操作效率的实现方法
C++中利用随机策略优化二叉树操作效率的实现方法
77 1

热门文章

最新文章