我是靠谱客的博主 朴实哑铃,这篇文章主要介绍C++基础,现在分享给大家,希望可以做个参考。

C++ 基础

输出

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

C与C++兼容

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

复制代码
1
2
3
4
5
6
7
8
9
#pragma once #ifdef _cplusplus extern "C" { #endif void test(int x, int y); #ifdef __cplusplus } #endif

引用类型

复制代码
1
2
3
4
5
6
7
8
9
void change(int&) { j = 11; } int i = 10; // 10这个内存地址 给了个别名 j int& j = i; change(j); cout << j << endl;

字符串

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// C 中 char str1[6] = {'h', 'e', 'l', ''}; char *str2 = "hello"; // C++ #include <string> 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();

命名空间

复制代码
1
2
3
4
5
6
7
8
namespace A { void test() {} } // :: 域作用符 A::B::test(); using namespace A::B test();

单例

复制代码
1
2
3
4
5
6
7
8
9
#pragma once class Instance { private: static Instance* instance; Instance(); public: static Instance* getInstance(); }
复制代码
1
2
3
4
5
6
7
8
9
10
11
#include "Instance.h" Instance * Instance::instance = 0; Instance::Instance() { } Instance* Instance::getInstance() { if (!instance) { instance = new Instance; } return instance; }

运算符重载

成员函数运算符重载

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#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;

非成员函数运算符重载

复制代码
1
2
3
4
5
6
Test2 operator+(const Test1& t1, const Test1& t2) { Test2 temp; temp.i = t1.i + t2.i; return temp; }

继承

复制代码
1
2
3
4
5
// 默认 private 私有继承 // 私有继承:父类的 public protected 编程了 private class Parent {} class Child : public Parent, private Parent1 {}

虚函数&纯虚函数

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

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

模板

函数模板

复制代码
1
2
3
4
5
template <typename T> T max(T a,T b) { return a > b ? a : b; }

最后

以上就是朴实哑铃最近收集整理的关于C++基础的全部内容,更多相关C++基础内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(49)

评论列表共有 0 条评论

立即
投稿
返回
顶部