zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

2023-09-14 08:57:16 时间

用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"}; // 联合初始化模式


Xcode中修改变量名、类名及字符串的替换操作  在做iOS开发代码优化的工作时,优化代码结构之前,我们应该先整理好工程的外貌,将文件和类的命名进行规范,在Xcode中为我们提供了方便而强大的名称修改功能。
Xcode与C++之游戏开发:Pong游戏 Xcode与C++之游戏开发:Pong游戏 接下来在前两天游戏骨架的基础上实现一个经典的乒乓球(Pong)游戏。游戏是这样的,一个球在屏幕上移动,玩家控制球拍来击打球。可以说乒乓球游戏是游戏开发者的 “Hello World” 项目。