0x01 数据类型
cout << sizeof(char) << '\n'
<< sizeof(short) << '\n'
<< sizeof(int) << '\n'
<< sizeof(long) << '\n'
<< sizeof(long long) << '\n'
<< endl;
每个环境定义的长度不一样,在mac下分别为
1
2
4
8
8
0x02 初始化
#include <iostream>
int main() {
using namespace std;
const char br{'\n'};
// 传统赋值
int age1 = 24;
// 下三种为C++11标准,使用{}
int age2 = {25};
// = 号可以省略
int age3{26};
// {}中不写值,表示:0
int age4{};
cout << age1 << br
<< age2 << br
<< age3 << br
<< age4 << br
<< endl;
return 0;
}
输出
24
25
26
0
0x03 C++11常量
wchar_t title[] = L"Hello";
char16_t name[] = u"Great";
char32_t book[] = U"Gentle";
0x04 原始字符串
使用 R"(
和 )"
来表示原生字符串,等价于 python 中的 '''
用法
string a{R"({"name":"a little boy"})"};
0x04 友元函数
- Time.h
class Time {
public:
Time();
Time(int hours, int minutes);
Time operator+(const Time &t) const;
Time operator*(double n) const;
void show() const;
friend Time operator*(double m, const Time &t);
private:
int hours;
int minutes;
};
- Time.cpp
#include "Time.h"
#include <iostream>
Time::Time() : hours(0), minutes(0) {}
Time::Time(int hours, int minutes) : hours(hours), minutes(minutes) {}
Time Time::operator+(const Time &t) const {
return Time{this->hours + t.hours, this->minutes + t.minutes};
}
Time Time::operator*(double n) const {
return Time{this->hours * (int) n, this->minutes * (int) n};
}
void Time::show() const {
using namespace std;
cout << "hour: " << this->hours << ", minutes: " << this->minutes << endl;
}
Time operator*(double m, const Time &t) {
return Time{t.hours * (int) m, t.minutes * (int) m};
}
- main.cpp
#include <iostream>
#include <string>
#include "Time.h"
using namespace std;
int main(int argc, char *argv[]) {
Time a{1, 20};
Time b{2, 10};
// 运算符重载
Time c = a + b;
c.show();
// 运算符重载
Time d = a * 3;
d.show();
// 这里触发了友元函数: operator*(double, Time &)
Time e = 100 * a;
e.show();
return 0;
}
0x05 enum class, 升级版枚举
enum class Day {
day1,day2
}
网友评论