cpp-d01

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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章