C++基础

C++ 基础

输出

cout << "Hello CMake." << endl;

C与C++兼容

c++中调用c代码中方法

#pragma once
#ifdef _cplusplus
extern "C" {
#endif
  void test(int x, int y);
#ifdef __cplusplus
}
#endif

引用类型

void change(int&) {
  j = 11;
}
int i = 10;
// 10这个内存地址 给了个别名 j
int& j = i;
change(j);
cout << j << endl;

字符串

// C 中
char str1[6] = {'h', 'e', 'l', '\0'};
char *str2 = "hello";
// C++ #include 
string str3 = "hello";
// 调用构造方法
string str4(str3);
string str5("hello");
// malloc = free
// new = delete
// new 数组 = delete[]
string *str6 = new string;
delete str6;
// 拼接字符串
string str5 = str1 + str3;
str1.append(str3);
// 输出
cout << str1.c_str() << endl;
// new 出的字符串
str6->c_str();

命名空间

namespace A {
  void test() {}
}
// :: 域作用符
A::B::test();
using namespace A::B
test();

单例

#pragma once

class Instance {
private:
  static Instance* instance;
  Instance();
public: 
  static Instance* getInstance();
}
#include "Instance.h"

Instance * Instance::instance = 0;

Instance::Instance() {
  
}

Instance* Instance::getInstance() {
  if (!instance) {
    instance = new Instance;
  }
  return instance;
}

运算符重载

成员函数运算符重载

#pragma once

class Test1 {
public:
  int i;
public:
  Text1 operator+(const Test1& t) {
    Test1 temp;
    temp.i = this->i + t.i;
    return temp;
  }
}
Test1 test1;
test1.i = 100;
Test1 test2;
test2.i = 200;
// 1.拷贝temp对象给一个临时对象
// 2.临时对象拷贝给test3
// 3.回收临时对象
Test1 test3 = test1 + test2;

非成员函数运算符重载

Test2 operator+(const Test1& t1, const Test1& t2) {
  Test2 temp;
  temp.i = t1.i + t2.i;
  return temp;
}

继承

// 默认 private 私有继承
// 私有继承:父类的 public protected 编程了 private
class Parent {}
class Child : public Parent, private Parent1 {}

虚函数&纯虚函数

构造方法永远不要设为虚函数,析构方法声明为虚函数。动态多态

纯虚函数,类似java中的抽象方法。

模板

函数模板

template 
T max(T a,T b) {
  return a > b ? a : b;
}

你可能感兴趣的:(音视频)