C/C++
使用VsCode开发C/C++
一.初始化环境:
通过RemoteSSH连接服务器并安装C++ Extension Pack插件. 1. 指定编译的输出文件添加后缀. 为了使用git管理代码同时忽略编译后的输入,需要指定编译输出路径或输出文件的后缀, 可以修改.vscode目录中的tasks.json和lunch.json. - tasks.json 的 -o参数指定后缀或者添加目录 - lunch.json 的program 指定为taskjson中输出路径的同样的路径 - ps.关于g++命令,可以参考g++ --help命令查看相应参数.
// tasks.json
{
"tasks": [
{
"type": "cppbuild",
"label": "C/C++: g++ build active file",
"command": "/usr/bin/g++",
"args": [
"-g",
"${file}",
"-o",
"${fileDirname}/${fileBasenameNoExtension}.o"
]
---------
// lunch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "g++ - Build and debug active file",
"type": "cppdbg",
"request": "launch",
"program": "${fileDirname}/${fileBasenameNoExtension}.o",
----
指针
- 等号左边的,这里称为左语句
- 等号右边的,成为右语句
// 指针声明,左语句
int v = 14;
int* p = &v;
// 从指针取值, 右语句同样使用*p取值。
int v2 = *p;
// 右语句,使用&v进行取指针
cout << v << endl;
cout << *p << endl;
cout << v2 << endl;
// 存放指针的数组
int* values[2];
values[0] = &v;
values[1] = &v;
cout << *values[0] << endl;
// 指针的指针,指针也可以作为一个数据, 由另一个指针指向它的内存地址
int** p2=&p; // p是一个指针, &p 指向P的指针(不是v)
cout << *p << endl;
cout << **p2 << endl; //取值用**p2
// point params test.
#include <iostream>
#include <string>
using namespace std;
class C2
{
private:
int v = 0;
string s = "123";
public:
string getS() {
return s;
}
int getV() {
return v;
}
};
// 传递类指针
void class_test1(C2 *c) {
cout << c->getS() << endl << c->getV() << endl;
}
// 传递类
void class_test2(C2 c) {
cout << c.getS() <<endl<< c.getV() << endl;
}
// 指针传参
void point_test1(int* v) {
// 输出值
cout << *v << endl;
}
void point_test2(string* v) {
//输出值
cout << *v << endl;
}
int main()
{
string string_v = "3";
int int_v = 5;
C2 t2;
point_test1(&int_v);
point_test2(&string_v);
class_test1(&t2);
class_test2(t2);
//cout << *p << endl;
std::cout << "Finish !\n";
}
智能指针
使用智能指针从而避免忘记回收内存导致的OOM问题。 - Standard Library 智能指针 - unique_ptr, unique智能指针,只有一个引用者 - shared_ptr,引用计数智能指针 - weak_ptr
std::unique_ptr<LargeObject> pLarge(new LargeObject());
pLarge->DoSomething();
适用于Windows Coms的智能指针
参考: C++ 智能指针
参考
手动编译
# C使用gcc
gcc -o hello hello.c
# C++使用g++,避免不链接Standard libiary的问题
g++ -o hello hello.cpp
C++ Template
使用注意事项,定义和声明放到header文件中,
// test.h
template<class T>
class Simple {
private:
int index;
public:
int getIndex();
};
// implement
template<class T> int Simple<T>::getIndex() {
return 0;
}
Errors
1. fatal error LNK1120: 1 个无法解析的外部命令
解决方案: Template声明放到header文件中, 参考:Template Class Implement