C++_对C数据类型的扩展

结构体

c++中定义结构体变量,可以省略struct关键字

c++结构提重可以直接定义函数,谓之成员函数(方法)

#include <iostream>
using namespace std;
struct stu {
	int num;
	char name[24];
	void price(void) {
		cout << "this is " << name << endl;
	}
};

int main() {
	stu st;
	cin >> st.num >> st.name;
	st.price();

	return 0;
}

联合

c++中定义联合体变量,可以省略union关键字,支持匿名联合

#include <iostream>
using namespace std;

int main(void) {
    union { //匿名联合,相当于局部变量
        int num;
        char c[4];
    };
    num = 0x12345678;
    cout << hex << (int)c[0] << " " << (int)c[1] << (int)c[2] << " " << c[3] <<endl;
}

#include <iostream>
using namespace std;

int main(void) {
	union { //匿名联合,相当于局部变量
		int num;
		char c[4];
	};
	num = 0x12345678;
	cout << hex << (int)c[0] << " " << (int)c[1] << (int)c[2] << " " << c[3] <<endl;
}

枚举类型

C++中定义枚举变量,可以省略enum关键字

C++中枚举是独立的数据类型,不能当做整型数使用

#include <iostream>
using namespace std;

int main() {
	enum COLOR {
		RED,GREEN,BULE
	};

	COLOR C = RED;
	cout << C << endl;
	return 0;
}
//输出值为0;C不能直接等于整数

布尔类型

C++中布尔(bool)是基本数据类型,专门表示逻辑值

布尔类型的字面值常量:

true表示逻辑真

false表示逻辑假

布尔类型本质:单字节的整数,使用1表示真,0表示假

任何基本类型都可以被隐式转换成布尔类型

#include <iostream>
using namespace std;

int main(int argc, const char *argv[])
{
	bool c;
	c = false;
	cout << c <<endl;
	cout << boolalpha << c << endl;
	c = 2 + 3;
	cout << boolalpha << c << endl;
	return 0;
}

//输出结果为0,false,true

C++对字符串的处理

C++专门设计了string类型表示字符串

string类型字符串定义

string s;//定义空字符串
//想字符串插入内容的三种方式
string s("hello");
string s = "hello"
string s = string("hello");

字符串拷贝

string s1 = "hello"
string s2 = s1;

字符串连接

string s1 = "hello", s2 = "world";
string s3 = s1 + s2;//s3:hello world
s1+=s2;//s1:hello world;

字符串比较

string s1 = "hello",s2 = "world";
if (s1 == s2) cout << s1 + s2 <<endl;
else cout << s1 << endl;

随机访问

//支持下标访问
string s = "hello";
s[0] = "H";

获取字符串长度

size_t size();
size_t length();

转换为C风格的字符串

const char *c_str();

字符串交换

void swap(string s1,string s2);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值