考场防编译错误专用。按"你想写什么"查找,每条都给出完整正确语法 和常见错误写法 对比。
配合 模板速查手册.md(高层套路)使用,本卡专注语法细节。
目录
1. 头文件:该 include 什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> #include <string> #include <vector> #include <algorithm> #include <queue> #include <stack> #include <map> #include <set> #include <cmath> #include <cstdlib> #include <cctype> #include <cstring> #include <numeric> #include <iomanip> #include <climits> #include <functional>
容易忘的头文件对照:
你要用什么
必须 include
忘了会怎样
accumulate
<numeric>
'accumulate' was not declared
sqrt, pow
<cmath>
'sqrt' was not declared
isalpha, isdigit, toupper
<cctype>
'isalpha' was not declared
abs(整数)
<cstdlib> 或 <cmath>
'abs' was not declared
setw, setprecision
<iomanip>
'setw' was not declared
INT_MAX
<climits>
'INT_MAX' was not declared
greater<int>
<functional>
'greater' was not declared
stoi, to_string
<string> (已含)
一般不会忘
strlen 等C函数
<cstring>
'strlen' was not declared
建议 :考试时一股脑全 include,不省那几行。宁可多 include 也不报错。
2. 头文件保护写法
1 2 3 4 5 6 7 8 9 10 11 12 #ifndef MYCLASS_H #define MYCLASS_H #endif #pragma once
错误写法 vs 正确写法:
1 2 3 4 5 6 7 8 9 class MyClass { ... };#ifndef MYCLASS_H #define MYCLASS_H class MyClass { ... };#endif
前向声明 (解决两个类互相引用):
1 2 3 4 5 6 class B ; class A { B* b; };
3. 变量与类型声明
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 int a = 10 ;double b = 3.14 ;char c = 'A' ;bool flag = true ;string s = "hello" ; int arr[100 ]; int arr[] = {1 , 2 , 3 }; int arr[5 ] = {0 }; char str[] = "hello" ; int matrix[10 ][20 ];int m[][3 ] = {{1 ,2 ,3 }, {4 ,5 ,6 }}; int * p; int * arr = new int [100 ]; int ** mat = new int *[n]; int x = 10 ;int & ref = x;
易错对比:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 int & ref; const int SIZE; int n; cin >> n;int arr[n]; int n; cin >> n;vector<int > v (n) ; constexpr int SIZE = 100 ;int arr[SIZE];
4. 函数:声明/定义/默认参数/重载
4.1 函数声明与定义分离
1 2 3 4 5 6 7 8 9 10 11 int add (int a, int b) ;void print (int x) ;int add (int a, int b) { return a + b; } void print (int x) { cout << x << endl; }
4.2 默认参数(只在声明写一次!)
1 2 3 4 5 6 7 void func (int a, int b = 10 , const string& s = "default" ) ;void func (int a, int b, const string& s) { cout << a << " " << b << " " << s << endl; }
错误:
1 2 3 4 5 6 7 8 9 void func (int a = 1 , int b, int c = 3 ) ; void func (int a, int b = 2 , int c = 3 ) ;
4.3 函数重载
1 2 3 4 5 6 7 8 int maxVal (int a, int b) ;double maxVal (double a, double b) ;int maxVal (int a, int b, int c) ;int func (int x) ;double func (int x) ;
4.4 const 参数 vs 非const参数
1 2 3 4 5 6 7 8 9 void func (int x) ;void func (const int x) ; void func (int & x) ; void func (const int & x) ; func (10 ); int a = 5 ; func (a);
5. 引用:& 的所有用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 void swap (int & a, int & b) { int t = a; a = b; b = t; } void print (const string& s) { cout << s; } print ("hello" ); int arr[100 ];int & at (int i) { return arr[i]; } at (5 ) = 42 ; const string& getName () const { return name; } int & bad () { int x = 10 ; return x; } int & good () { static int x = 10 ; return x; }
易错:
1 2 3 4 5 6 7 8 9 void func (int & x) {}func (10 ); string& ref = string ("hi" ); const string& ref2 = string ("hi" );
6. 指针:* 的所有用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 int x = 10 ;int * p = &x; cout << *p; *p = 20 ; void func (int * p) { *p = 100 ; } int a = 5 ;func (&a); const int * p1; int * const p2 = &x; const int * const p3 = &x; int * p = nullptr ; if (p != nullptr ) { *p; }int * arr = new int [100 ];arr[0 ] = 1 ; arr[50 ] = 2 ; delete [] arr; MyClass obj; MyClass* p = &obj; p->method (); (*p).method (); class A { int x; public : void setX (int x) { this ->x = x; } A& add (int n) { this ->x += n; return *this ; } };
7. 类:完整语法清单
7.1 类的基本结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 class ClassName {private : int data; string name; int * arr; protected : int protectedData; public : ClassName (); ClassName (int d); ClassName (int d, const string& n); ~ClassName (); int getData () const ; void setData (int d) ; static int getCount () ; ClassName operator +(const ClassName& rhs) const ; ClassName& operator =(const ClassName& rhs); int & operator [](int i); friend ostream& operator <<(ostream& os, const ClassName& obj); };
7.2 成员函数定义(.cpp 中)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include "ClassName.h" int ClassName::getData () const { return data; } void ClassName::setData (int d) { data = d; } int ClassName::getCount () { return count; } ClassName::ClassName () : data (0 ), name ("" ), arr (nullptr ) { } ClassName::ClassName (int d) : data (d), name ("" ) { arr = new int [10 ]; } ClassName::~ClassName () { delete [] arr; }
易错对比:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 class A { int x; } class A { int x; }; int getData () const { return data; } int A::getData () const { return data; }
7.3 访问控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class A { int x; private : int y; protected : int z; public : int w; }; struct B { int x; };
8. 构造函数:所有写法
8.1 初始化列表(强烈推荐)
1 2 3 4 5 6 7 8 9 10 11 12 13 class Student { int id; const string name; int & score; int * data; public : Student (int id, const string& n, int & s) : id (id), name (n), score (s), data (nullptr ) { data = new int [10 ]; } };
易错:
1 2 3 4 5 6 7 8 9 10 11 12 13 class A { const int x; int & ref; public : A (int val, int & r) { x = val; ref = r; } }; A (int val, int & r) : x (val), ref (r) {}
8.2 委托构造(C++11)
1 2 3 4 5 6 7 class A { int x, y; public : A () : A (0 , 0 ) {} A (int x) : A (x, 0 ) {} A (int x, int y) : x (x), y (y) {} };
8.3 explicit(禁止隐式转换)
1 2 3 4 5 6 7 class Fraction {public : explicit Fraction (int n) : num(n), den(1 ) { } }; Fraction f = 5 ; Fraction f (5 ) ; Fraction f = Fraction (5 );
8.4 = delete(禁止拷贝)
1 2 3 4 5 6 class NonCopyable {public : NonCopyable () = default ; NonCopyable (const NonCopyable&) = delete ; NonCopyable& operator =(const NonCopyable&) = delete ; };
8.5 = default(用默认的)
1 2 3 4 5 6 class A {public : A () = default ; A (const A&) = default ; ~A () = default ; };
9. const:所有出现位置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 const int SIZE = 100 ;constexpr int MAX = 1000 ; void func (const string& s) ;void func (const vector<int >& v) ;const int & getRef () const ;class A { int x; public : int getX () const { return x; } void setX (int x) { this ->x = x; } }; const A obj;obj.getX (); obj.setX (5 ); class A { const int id; public : A (int i) : id (i) {} }; const int * p; int * const p = &x;
const 一致性规则(高频考点):
1 2 3 4 5 6 7 8 9 10 int getX () const ;void print () const ;bool empty () const ;int A::getX () const { ... } void A::print () const { ... }
10. static:成员和函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Counter {private : int id; static int count; static const int MAX = 100 ; public : Counter () { id = ++count; } ~Counter () { --count; } static int getCount () ; }; int Counter::count = 0 ; int Counter::getCount () { return count; }
易错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 static int getCount () { return id; } static int Counter::getCount () { ... } int Counter::getCount () { ... }
11. 动态内存:new/delete 完整写法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 int * p = new int ; int * p = new int (42 ); int * p = new int (); delete p; int * arr = new int [100 ]; int * arr = new int [100 ](); arr[0 ] = 1 ; delete [] arr; int ** mat = new int *[rows];for (int i = 0 ; i < rows; i++) mat[i] = new int [cols]; for (int i = 0 ; i < rows; i++) delete [] mat[i]; delete [] mat; MyClass* obj = new MyClass (10 ); obj->method (); delete obj;MyClass* arr = new MyClass[5 ]; delete [] arr;
易错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 int * arr = new int [100 ];delete arr; void func () { int * p = new int (10 ); } int * p = new int (10 );delete p;*p = 20 ; int * p = new int (10 );delete p;delete p; class A { int * p; };A a; A b = a;
12. 运算符重载:每个运算符的精确写法
12.1 算术运算符(成员函数)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Fraction { int num, den; public : Fraction operator +(const Fraction& r) const { return Fraction (num * r.den + r.num * den, den * r.den); } Fraction operator -(const Fraction& r) const { ... } Fraction operator *(const Fraction& r) const { ... } Fraction operator /(const Fraction& r) const { ... } Fraction& operator +=(const Fraction& r) { *this = *this + r; return *this ; } Fraction& operator -=(const Fraction& r) { ... } };
12.2 比较运算符(成员函数,返回 bool)
1 2 3 4 5 6 7 8 9 10 11 12 13 class Fraction {public : bool operator <(const Fraction& r) const { return num * r.den < r.num * den; } bool operator ==(const Fraction& r) const { return num * r.den == r.num * den; } bool operator !=(const Fraction& r) const { return !(*this == r); } bool operator >(const Fraction& r) const { return r < *this ; } bool operator <=(const Fraction& r) const { return !(r < *this ); } bool operator >=(const Fraction& r) const { return !(*this < r); } };
12.3 下标运算符(两个版本)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 class Array { int * data; public : int & operator [](int i) { return data[i]; } const int & operator [](int i) const { return data[i]; } }; Array arr; arr[0 ] = 10 ; const Array carr;int x = carr[0 ];
12.4 自增自减(前置 vs 后置)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Counter { int val; public : Counter& operator ++() { ++val; return *this ; } Counter operator ++(int ) { Counter old = *this ; ++val; return old; } Counter& operator --() { --val; return *this ; } Counter operator --(int ) { Counter old = *this ; --val; return old; } };
12.5 流插入/提取(必须友元或类外)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class Fraction { int num, den; public : friend ostream& operator <<(ostream& os, const Fraction& f); friend istream& operator >>(istream& is, Fraction& f); }; ostream& operator <<(ostream& os, const Fraction& f) { os << f.num << "/" << f.den; return os; } istream& operator >>(istream& is, Fraction& f) { is >> f.num >> f.den; return is; }
易错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class A { ostream& operator <<(ostream& os) { ... } }; ostream& operator <<(ostream& os, const A& a) { ... } ostream& operator <<(ostream& os, const A& a) { os << a.x; } Counter operator ++() { ... } Counter operator ++(int ) { ... }
12.6 函数调用运算符(仿函数)
1 2 3 4 5 6 7 8 9 10 11 12 class Comparator { bool ascending; public : Comparator (bool asc) : ascending (asc) {} bool operator () (int a, int b) const { return ascending ? a < b : a > b; } }; Comparator cmp (true ) ;cout << cmp (3 , 5 ); sort (arr, arr + n, cmp);
12.7 类型转换运算符
1 2 3 4 5 6 7 8 9 10 11 class Fraction { int num, den; public : operator double () const { return (double )num / den; } }; Fraction f (1 , 2 ) ;double d = f;
13. 继承:完整语法
13.1 单继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Base {protected : string name; public : Base (const string& n) : name (n) {} void intro () { cout << name; } }; class Derived : public Base { int extra; public : Derived (const string& n, int e) : Base (n), extra (e) {} };
13.2 多重继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class A {public : void funcA () {} }; class B {public : void funcB () {} }; class C : public A, public B {public : void funcC () { funcA (); funcB (); } };
13.3 继承方式对照
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 class Base {public : int pub; protected : int prot; private : int priv; }; class D1 : public Base { }; class D2 : protected Base { }; class D3 : private Base { };
13.4 调用基类成员
1 2 3 4 5 6 7 8 9 10 11 12 13 14 class Base {public : void func () { cout << "Base" ; } }; class Derived : public Base {public : void func () { cout << "Derived" ; } void test () { func (); Base::func (); } };
14. 虚函数/多态:完整语法
14.1 虚函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class Animal {public : virtual void speak () const { cout << "..." << endl; } virtual ~Animal () {} }; class Dog : public Animal {public : void speak () const override { cout << "Woof" << endl; } }; Animal* a = new Dog (); a->speak (); Animal& ref = *a; ref.speak ();
14.2 纯虚函数 / 抽象类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Shape {public : virtual double area () const = 0 ; virtual void print () const = 0 ; virtual ~Shape () {} }; class Circle : public Shape { double r; public : Circle (double r) : r (r) {} double area () const override { return 3.14159 * r * r; } void print () const override { cout << "Circle" ; } };
易错:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 class Base { ~Base () {} }; class Derived : public Base { int * p; ~Derived () { delete p; } };Base* b = new Derived (); delete b; class Base { virtual ~Base () {} };class Base { virtual void f (int ) const ; };class Derived : public Base { void f (int ) override {} }; class Derived : public Base { void f (int ) const override {} }; class Base { virtual void a () = 0 ; virtual void b () = 0 ; };class D : public Base { void a () override {} }; D d; void func (Animal a) { a.speak (); } Dog d; func (d); void func (Animal& a) { a.speak (); }void func (Animal* a) { a->speak (); }
14.3 final(禁止继承/覆盖)
1 2 3 4 5 6 7 8 class A final { }; class Base { virtual void f () final ; };
14.4 RTTI:typeid 和 dynamic_cast
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <typeinfo> Animal* a = new Dog (); cout << typeid (*a).name (); if (typeid (*a) == typeid (Dog)) { } Dog* d = dynamic_cast <Dog*>(a); if (d != nullptr ) { d->bark (); } Dog& dr = dynamic_cast <Dog&>(*a);
注意:dynamic_cast 要求基类至少有一个 virtual 函数!
1 2 3 4 5 6 7 8 class Base { int x; };class Derived : public Base { int y; };Base* b = new Derived (); Derived* d = dynamic_cast <Derived*>(b);
15. 模板:完整语法
15.1 函数模板
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 template <typename T> T myMax (T a, T b) { return a > b ? a : b; } cout << myMax (3 , 5 ); cout << myMax (3.14 , 2.71 ); cout << myMax <int >(3 , 5 ); template <typename T1, typename T2>void print (T1 a, T2 b) { cout << a << " " << b; }
15.2 类模板(实现必须放 .h/.hpp!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #ifndef STACK_HPP #define STACK_HPP template <typename T, int N = 100 > class Stack {private : T data[N]; int top; public : Stack () : top (0 ) {} void push (const T& x) { data[top++] = x; } T pop () { return data[--top]; } bool empty () const { return top == 0 ; } }; #endif Stack<int > s; Stack<double , 50 > s2;
15.3 类外定义成员(每个都要带 template 前缀)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 template <typename T>class Stack { T data[100 ]; int top; public : void push (const T& x) ; T pop () ; }; template <typename T>void Stack<T>::push (const T& x) { data[top++] = x; } template <typename T>T Stack<T>::pop () { return data[--top]; }
易错:
15.4 函数模板全特化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 template <typename T>void print (T x) { cout << "[UNKNOWN] " << x; } template <>void print <int >(int x) { cout << "[INT] " << x; } template <>void print <double >(double x) { cout << "[DOUBLE] " << x; } print (10 ); print (3.14 ); print ("hi" );
15.5 显式实例化
1 2 3 4 5 6 7 8 9 10 11 template <typename T> class Stack { void push (const T&) ; };template <typename T>void Stack<T>::push (const T& x) { }template class Stack <int >; template class Stack <double >;
16. STL 容器:声明+方法完整表
16.1 vector
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <vector> vector<int > v; vector<int > v1 (n) ; vector<int > v2 (n, 5 ) ; vector<int > v3 = {1 , 2 , 3 }; vector<vector<int >> mat (n, vector <int >(m, 0 )); v.push_back (5 ); v.pop_back (); v.size (); v[i]; v.at (i); v.front (); v.back (); v.empty (); v.clear (); v.begin (); v.end (); v.insert (v.begin () + i, val); v.erase (v.begin () + i); v.resize (n); for (int i = 0 ; i < v.size (); i++) cout << v[i];for (int x : v) cout << x; for (auto & x : v) x *= 2 ;
16.2 string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <string> string s = "hello" ; string s2 (10 , 'a' ) ; string s3 = s.substr (1 , 3 ); string s4 = s + " world" ; s.size (); s[i]; s.find ("ll" ); s.find ('l' ); s.replace (0 , 2 , "HI" ); s.insert (2 , "XX" ); s.erase (1 , 2 ); s += " world" ; s.compare (s2); s.c_str (); stoi (s); stol (s); stod (s); to_string (123 ); getline (cin, s);
16.3 stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <stack> stack<int > stk; stk.push (1 ); stk.pop (); stk.top (); stk.empty (); stk.size (); stack<int > temp; while (!stk.empty ()) { cout << stk.top (); temp.push (stk.top ()); stk.pop (); } while (!temp.empty ()) { stk.push (temp.top ()); temp.pop (); }
16.4 queue
1 2 3 4 5 6 7 8 #include <queue> queue<int > q; q.push (1 ); q.pop (); q.front (); q.back (); q.empty (); q.size ();
16.5 priority_queue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #include <queue> priority_queue<int > pq; pq.push (3 ); pq.push (1 ); pq.push (5 ); pq.top (); pq.pop (); priority_queue<int , vector<int >, greater<int >> minpq; minpq.push (3 ); minpq.push (1 ); minpq.top (); priority_queue<pair<int ,int >> ppq; ppq.push ({5 , 101 }); ppq.push ({3 , 102 }); ppq.top (); ppq.top ().first; ppq.top ().second;
16.6 map
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <map> map<string, int > m; m["tom" ] = 90 ; m["tom" ]++; m.insert ({"jerry" , 85 }); m.count ("tom" ); m.find ("tom" ); m.erase ("tom" ); m.size (); m.empty (); for (auto & p : m) { cout << p.first << ": " << p.second; } for (auto it = m.begin (); it != m.end (); ++it) { cout << it->first << it->second; }
16.7 set
1 2 3 4 5 6 7 8 9 10 11 #include <set> set<int > s; s.insert (3 ); s.insert (3 ); s.count (3 ); s.find (3 ); s.erase (3 ); s.size (); for (int x : s) cout << x;
16.8 常用算法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 #include <algorithm> #include <numeric> vector<int > v = {3 , 1 , 4 , 1 , 5 }; sort (v.begin (), v.end ()); sort (v.rbegin (), v.rend ()); sort (v.begin (), v.end (), greater <int >()); sort (v.begin (), v.end (), less <int >()); sort (v.begin (), v.end (), [](int a, int b) { return a > b; }); sort (stu.begin (), stu.end (), [](const Student& a, const Student& b) { if (a.score != b.score) return a.score > b.score; return a.id < b.id; }); find (v.begin (), v.end (), 4 ); count (v.begin (), v.end (), 1 ); count_if (v.begin (), v.end (), [](int x) { return x > 60 ; });*max_element (v.begin (), v.end ()); *min_element (v.begin (), v.end ()); int sum = accumulate (v.begin (), v.end (), 0 ); double avg = accumulate (v.begin (), v.end (), 0.0 ) / v.size (); reverse (v.begin (), v.end ());reverse (s.begin (), s.end ()); swap (a, b);
17. string:所有常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 #include <string> #include <cctype> string s1 = "hello" ; string s2 (5 , 'a' ) ; string s3 (s1, 1 , 3 ) ; s.size (); s.length (); s.empty (); s[0 ]; s.back (); s.front (); s.find ("lo" ); s.find ('l' ); s.rfind ('l' ); if (s.find ("xx" ) != string::npos) { }s.substr (2 ); s.substr (0 , 3 ); s += " world" ; s.push_back ('!' ); s.insert (2 , "XX" ); s.erase (1 , 2 ); s.replace (0 , 2 , "HI" ); s.clear (); s == "hello" ; s < "world" ; stoi ("123" ); stol ("1234567890" );stod ("3.14" );to_string (123 ); s.c_str (); char c = 'A' ;isalpha (c); isdigit (c); isalnum (c); isspace (c); isupper (c); islower (c); toupper (c); tolower (c); for (char & c : s) { c = toupper (c); }
18. IO 格式化:所有操纵符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 #include <iomanip> cout << fixed << setprecision (2 ) << 3.14159 ; cout << setprecision (4 ) << 3.14159 ; cout << left << setw (10 ) << "Name" ; cout << right << setw (10 ) << "Name" ; cout << setw (10 ) << "Name" ; cout << setfill ('0' ) << setw (5 ) << 42 ; cout << setfill ('*' ) << setw (5 ) << "Hi" ; cout << setfill ('0' ) << setw (2 ) << hour << ":" << setfill ('0' ) << setw (2 ) << minute << ":" << setfill ('0' ) << setw (2 ) << second; cout << dec << 255 ; cout << oct << 255 ; cout << hex << 255 ; cout << showbase << oct << 255 ; cout << showbase << hex << 255 ; cout << showbase << uppercase << hex << 255 ; cout << noshowbase; cout << boolalpha << true ; cout << noboolalpha << true ; cout << showpoint << 3.0 ; cout << noshowpoint << 3.0 ; int x; cin >> x;string s; cin >> s; getline (cin, s); int n; cin >> n;cin.ignore (); getline (cin, s);while (cin >> x) { ... } int n; cin >> n; while (n--) { ... }
IO 操纵符持续性:
1 2 3 4 5 6 7 cout << fixed << setprecision (2 ); cout << 3.14159 << endl; cout << 2.71828 << endl; cout << setw (10 ) << "A" << "B" ;
19. 控制流:易错写法
19.1 switch(记得 break!)
1 2 3 4 5 6 7 8 9 10 11 12 int x;switch (x) { case 1 : cout << "one" ; break ; case 2 : cout << "two" ; break ; default : cout << "other" ; break ; }
19.2 范围 for 循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 vector<int > v = {1 , 2 , 3 }; for (int x : v) { cout << x; } for (int & x : v) { x *= 2 ; } for (char c : s) { cout << c; } for (char & c : s) { c = toupper (c); } for (auto & p : m) { cout << p.first << p.second; }
19.3 break 和 continue
1 2 3 4 5 6 7 8 9 10 11 12 13 for (int i = 0 ; i < n; i++) { if (v[i] == target) { found = true ; break ; } } for (int i = 0 ; i < n; i++) { if (v[i] < 0 ) continue ; sum += v[i]; }
20. 类型转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 int x = (int )3.14 ;double d = (double )x;int x = static_cast <int >(3.14 );double d = static_cast <double >(x);int i = 'A' ; char c = 65 ; double d = 10 ; int i = 3.14 ; int a = 1 , b = 3 ;double r = (double )a / b; double r = static_cast <double >(a) / b;char c = '5' ;int digit = c - '0' ; int n = 7 ;char ch = n + '0' ; int n = stoi ("123" );string s = to_string (456 );
21. 编译错误大全:报错→原因→修法
30+ 条常见编译错误速查。
类与成员
报错信息
原因
修法
expected ';' after class definition 或 expected ';' at end of class
类 } 后漏分号
加 };
expected ';' before 某标识符
上一行漏分号
在上一行末加 ;
undefined reference to 'Xxx::func()'
成员函数声明了但没定义
在 .cpp 补 Xxx::func() 定义
undefined reference to 'Xxx::count'
静态成员没类外定义
.cpp 加 int Xxx::count = 0;
no matching function for call to 'Xxx::func()'
函数签名不匹配
检查参数个数/类型/const
cannot declare member function to have static linkage
静态函数定义加了 static
定义时不加 static
'func' is not a member of 'Xxx'
函数名拼错或忘加 Xxx::
加 Xxx:: 或修正拼写
redefinition of 'Xxx::func()'
函数定义了两次
删除重复定义
const 相关
报错信息
原因
修法
passing 'const Xxx' as 'this' argument discards qualifiers
const 对象调了非 const 函数
函数声明加 const
assignment of member 'Xxx::data' in read-only object
const 函数里修改了成员
去掉 const 或用 mutable
no matching function for call (const 版)
声明有 const 定义没 const
定义也加 const
include 与作用域
报错信息
原因
修法
'xxx' was not declared in this scope
忘 include / 拼写错 / 没 using namespace
补 include / 检查拼写 / 加 using namespace std;
'cout' was not declared
忘 #include <iostream> 或 using namespace std
补上
'string' was not declared
忘 #include <string> 或 using namespace std
补上
'accumulate' was not declared
忘 #include <numeric>
补上
'sqrt' was not declared
忘 #include <cmath>
补上
'setw' was not declared
忘 #include <iomanip>
补上
redefinition of 'class Xxx'
头文件没保护 / 重复 include
加 #ifndef 或 #pragma once
继承与多态
报错信息
原因
修法
cannot allocate an object of abstract type 'Xxx'
纯虚函数没全实现
派生类实现所有 = 0
marked 'override' but does not override any virtual function
签名不一致
检查参数/const/返回值是否和基类一致
no matching function for call to 'Xxx::Xxx()'
派生类需要默认构造但没提供
加默认构造函数
invalid use of incomplete type 'class Xxx'
两个头文件互相 include
用前向声明 class Xxx;
request for member 'func' is ambiguous
多重继承同名冲突
加 Base::func() 显式指定
cannot dynamic_cast ... (source type is not polymorphic)
基类没有 virtual 函数
基类加至少一个 virtual
模板
报错信息
原因
修法
undefined reference to 'Stack<int>::push(int const&)
模板实现放 .cpp
搬到 .h/.hpp
expected ';' before '<' token
类外定义忘 template<typename T>
加前缀
too few template-parameter-lists
类外定义忘 <T>
Stack<T>::func
no matching function for call to 'max(T, T)'
类型不一致
max<int>(3, 3.14) 显式指定
expected primary-expression before '>' token
模板参数不匹配
检查参数类型/个数
运算符重载
报错信息
原因
修法
no match for 'operator<<'
没重载 << 或不是友元
加 friend ostream& operator<<
no match for 'operator<'
sort 缺比较
补 operator< 或传 lambda
candidate is: Xxx operator++()
前置后置搞混
后置加 int 哑参数
cannot bind 'std::ostream' lvalue to 'const std::basic_ostream<char>&'
<< 返回类型错
返回 ostream& 不是 void
运行时错误
现象
原因
修法
Segmentation fault / 段错误
空指针/越界/野指针访问
检查指针和下标
double free / 堆损坏
浅拷贝导致重复释放
补深拷贝三件套
程序卡死无输出
死循环 / 等待输入
检查循环条件和输入
输出后崩
析构时释放已释放内存
检查析构和赋值运算符
结果全 0
忘记读输入 / 初始化
检查 cin 和初始化
链接错误
报错信息
原因
修法
undefined reference to 'WinMain'
没有 main 函数
加 int main()
multiple definition of 'xxx'
全局变量/函数定义在头文件中
只声明在 .h,定义放 .cpp
cannot find -lxxx
缺库
考试一般不会遇到
22. 考前必背 30 条语法口诀
考前最后看一遍这 30 条,能避免 90% 的编译错误。
类声明后必须有分号 :class A { ... }; ← 分号!
成员函数定义加 ClassName:: :int A::getX() const { ... }
const 两边一致 :声明和定义的 const 必须完全相同
默认参数只写声明 :.h 写 = 0,.cpp 不写
静态成员类外定义 :int A::count = 0; 不能忘
静态函数定义不加 static :int A::getCount() { ... }
const/引用成员用初始化列表 :A(int x) : id(x), ref(r) {}
new 配 delete,new[] 配 delete[]
有指针成员写三件套 :拷贝构造 + 赋值运算符 + 析构
赋值运算符 5 步 :自检→释放→复制标量→分配→逐个复制→return *this
基类析构加 virtual :virtual ~Base() {}
override 让编译器检查 :void func() override
抽象类纯虚全实现才能实例化
多态用指针/引用 ,值传递会对象切片
dynamic_cast 要有多态 (基类至少一个 virtual)
<< 重载必须友元 ,返回 ostream&
后置 ++ 加 int 哑参数 :Counter operator++(int)
模板实现放 .h/.hpp ,不能放 .cpp
模板类外定义带 template<typename T> 和 <T>
头文件加保护 :#ifndef 或 #pragma once
getline 前要 ignore :cin >> n; cin.ignore(); getline(cin, s);
accumulate 初值 0.0 得 double ,0 得 int
priority_queue 小顶堆 :priority_queue<int, vector<int>, greater<int>>
map 自动按 key 排序 ,set 自动去重
元素间空格末尾不加 :if (i+1 < n) cout << " ";
前导零用 setw+setfill :setfill('0') << setw(2) << 8
stoi/to_string 在 <string> 里
accumulate 在 <numeric> 里 (不是 <algorithm>)
toupper/tolower 返回值不改原字符 ,要 c = toupper(c)
万能开头一次 include 全 :iostream/string/vector/algorithm/queue/stack/map/set/cmath/iomanip/numeric/cctype
使用建议 :考前把第 22 节(30 条口诀)背熟,考试中遇到编译错误翻第 21 节对照表,写代码时不确定语法翻对应章节。