[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"};  // 联合初始化模式
原文地址:https://www.cnblogs.com/YouXianMing/p/4316601.html