经验

标准输入输出流

用scanf读取string类,出现问题:

scanf("%s", str.c_str());
assert(str.length() != 0);    // assert failed.

string与c标准混用是危险的。现在正在查清原因。

新的问题:如何读取不定长、不定个数的字符数组?
法1:申请足够长的字符数组作为buffer

cin的重置

使用到了clear和sync函数

char ch;
while(cin >> ch){
    ...
}
cin.clear();
cin.sync();

链表野指针的问题

链表的next区域的申请内存步骤:

  • 若先从原节点调到next,再new,则原节点的next区域变为野指针,因为此时的p与上一节点的next已经没有关联。

  • 因此,要在原节点的next就设置new,如下所示

    p->next = new ListNode(x);
    p = p->next;

无参数构造函数的使用

在main函数中构造没有参数的类,类后不应该加括号。

在类内实现的尴尬bug

忘了加花括号并且没看见波浪线的尴尬debug
无法解析的外部符号 "public: __thiscall Student::~Student(void)" (??1Student@@QAE@XZ),该符号在函数 _main 中被引用

头文件#ifndef, #define, #endif的作用

当多个cpp调用头文件并编译时,没有上面的设置,会重复调用头文件的声明,导致编译错误。

纯虚函数除了定义,还必须有实现。

如:
class Polygon{
public:
virtual ~Polygon() = 0;
};

类外实现:
Polygon::~Polygon() {}

变量的声明:从右往左读以理解其含义

Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:把一个声明从右向左读。
例子:
char * const cp; // cp is a const pointer to char.
const char * p; // p is a pointer to const char.

操作符优先级

http://en.cppreference.com/w/cpp/language/operator_precedence
三目运算符的结合性是从右到左,优先级低于加法运算符,高于赋值运算符。
以下代码会出错:

string s1 = "test", s2 = "add", s = "just";
s = (s1.empty())?s:s1 + (s2.empty())?:s:s2;

必须要对每个三目运算符表达式加括号才能正确运行。

代码有毒

  • +的优先级要高于按位与&
原文地址:https://www.cnblogs.com/severnvergil/p/6580144.html