常见错误记录C++

来源:互联网 发布:表情包软件 编辑:程序博客网 时间:2024/05/18 05:58

1、undefined reference to意思是类的静态成员在全局下定义后要在类外初始化;

class A{static A* w;public:A(){}~A() {}};int A::w = NULL;

 

 

2、成员函数没有定义为static类型

cannot call member function ' without object

3、文件组织格式

template定义等都在h文件,不需要包含其他头文件

调用在c文件,包含template的h文件

4、公有的静态成员变量需要在“外部”初始化,才能被其他成员函数使用。

如声明时为static const char * const pcV;  ---- static只能放在声明处。

初始化必须为类似const char * const an::pcV="ab";  --- 必须完整定义。


5、linux下编译, 头文件也区分大小写

No such file or directory

6. static_cast

static_cast<FilterRelation *>(pNode) -- 必须两侧加括号括起来。如果是<FilterRelation>则会产生一个临时对象;而<FilterRelation &>则不会。


7. 子类覆盖基类的成员函数,必须在子类中重新声明,否则失败;

  • 而声明在子类的哪个区域下,没有限制!
  • 使用指针,引用方式通过基类调用,则要求在基类的public区;(这时即使子类声明在private区也可以被实际调用)
  • 而如果直接调用子类的成员函数,而子类声明不在public区,则不可以调用;

8. 注意构造和析构顺序

  • 在基类的析构函数中不能调用派生类的成员函数,因为子类已经被析构了!!!这时只能覆盖析构函数。
  • 同理,基类的析构函数也不要调用虚函数,即使调用虚函数,C++编译器也会只选择基类的函数定义;

9. "a" 被以引用方式传递,则解析为constchar [2];有时候解析为const char *;

     string("a")被解析为string,二者都不是string &

using namespace std;
void fun(string s)
{
    cout << s << endl;
}

void fun2(string & s)
{
    cout << s << endl;
}

int main()
{
fun("abc"); --- ok

/*
test.cc:22: error: invalid initialization of non-const reference of type 'std::string&' from a temporaryof type 'const char*'
test.cc:14: error: in passing argument 1 of 'void fun2(std::string&)'
*/
fun2("abc");

/*
test.cc:23: error: invalid initialization of non-const reference of type 'std::string&' from a temporary of type 'std::string'
*/
fun2(string("abc"));

string ss("abc");
fun2(ss);  -- ok
}

10. 如果基类的构造函数有参数输入(无缺省值),则子类必须自定义构造函数,不能使用默认的构造函数,因为无法预知基类如何构造!

11. 别忘了using namespace;

12. 别忘了头文件的#ifndef 检查,否则可能出现重复定义错误!!!

13. boost::shared_ptr<mytype> xdata; 共享指针的模板参数为type,而不是type的指针!但得到的是type的之共享指针!

14. 删除指针容器中的元素,一定要小心,别忘了释放指针所指的内存;当针对迭代器执行erase之后,迭代器会失效,所以要最后erase迭代器,先释放迭代器所指的内存。

    delete (*it);

    *it = NULL;

    _childRule.erase(it);

15. 常引用

  • int a ;
  • const int &ra=a;
  • ra=1; //错误
  • a=1; //正确

16. inline定义放错位置,没有放置在头文件中,导致ld时找不到此函数定义!!!

17. 打印string时,没有使用c_str()成员函数进行转换,导致打印不出来!

18. 将const vector<char *> &赋给了 vector<char *> &,导致编译不过。

19. vector容器的引用,delete元素[0],则“[0]下标”变为原来[1]的元素!相当于迭代器失效。

20. 在union中不要包含对象,一般编译器会有如下错误:

with constructor not allowed in union

with destructor not allowed in union

with copy assignment operator not allowed in union

21. protected member func和private一样只能被其他成员函数使用,不能显示调用。基类的protected成员函数,public方式继承,在派生类中还是protected类型。


子类不能继承的:
    its constructor and its destructor
    its operator=() members
    its friends


0 0