赋值语句——多种赋值方式

简单赋值:

#include
using namespace std;

int main() {
// 简单赋值
int a = 10;
int b = 20;
string c = “Hello, World!”;

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

return 0;

}

串联赋值:

#include
using namespace std;

int main() {
// 串联赋值
int a, b, c;
a = b = c = 10;

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

return 0;

}

成组赋值:

#include
#include
using namespace std;

int main() {
// 使用元组进行成组赋值
auto [a, b, c] = make_tuple(1, 2, 3);

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

return 0;

}

结构赋值:

#include
#include
using namespace std;

int main() {
// 元组解构赋值
tuple<int, int, int> numbers = {1, 2, 3};
auto [a, b, c] = numbers;

cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;

// 结构体解构赋值
struct Person {
    string name;
    int age;
};

Person person = {"Alice", 30};
auto [name, age] = person;

cout << "name = " << name << endl;
cout << "age = " << age << endl;

return 0;

}

条件赋值:

#include
using namespace std;

int main() {
int a = 10;
int b = 20;
int max_value = (a > b) ? a : b;

cout << "max_value = " << max_value << endl;

return 0;

}

交换赋值:

#include
using namespace std;

int main() {
int a = 10;
int b = 20;

cout << "交换前:" << endl;
cout << "a = " << a << ", b = " << b << endl;

// 使用临时变量进行交换赋值
int temp = a;
a = b;
b = temp;

cout << "交换后:" << endl;
cout << "a = " << a << ", b = " << b << endl;

return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值