Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1316916
  • 博文数量: 244
  • 博客积分: 1039
  • 博客等级: 少尉
  • 技术积分: 1562
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-06 09:40
文章分类

全部博文(244)

文章存档

2021年(2)

2019年(6)

2018年(2)

2014年(1)

2013年(187)

2012年(47)

分类: C/C++

2013-03-26 17:48:56

C++编程常见错误cannot have cv-qualifier错误或者undefined reference to `vtable for ...'或者'because the following virtual functions are pure within 'Test' '或者'uninitialized member 'Test::a' with 'const' type 'const int' 

1、cannot have cv-qualifier

   不能有CV限定符,在C++中CV限定符指const和volatile。

    a、在C++中,普通函数(非类的成员函数)不能有CV限定,即const和volatile限定。

          即非类的成员行数,用const进行修饰:

          int test() const                     //这是不对的,普通函数(非成员函数不能有CV约束)

          {

                      //实现

          }

    b、在C++中,静态成员函数(static成员函数)不能有CV限定,即const和volatile限定。

          即类的静态成员函数,也不能有CV约束:

          class   Test

          {

                 public:

                       static  int  test_fun()  const;                 //这个是不允许的。

          }

2、undefined reference to `vtable for ...'

    产生问题的原因是::

            基类中声明了virual 方法(不是纯虚方法),但是没有实现。在子类中实现了,当子类创建对象时,就出现这个问题。

     class   Base

     {

                 public:

                      virtual  int run();

     };

     class  Test:public Base              //必须实现run才可以

     {

                public:

                      Test()

                      {

                      }

     };

     在Test中必须实现run,否则Test不能创建对象,创建对象,编译时会报 undefined reference to `vtable for ...' 这种错误。

     如果是“纯虚函数”,即 virtual int run() = 0;编译时会报" because the following virtual functions are pure within 'Test' "

     如果在基类中实现了虚函数,或者在子类中实现纯虚函数或虚函数,就不会报错。

     包含有虚函数的类,是不能创建对象的。

3、在C++中,const成员变量也不能在类定义处初始化,只能通过构造函数初始化列表进行,并且必须有构造函数。

例如:

       class  Test

       {

                    private:

                         const   int a;

                    public:

                         Test()

                         {

                                     a = 0;                 //错误的

                         }

       };
      在编译时,会报"uninitialized member 'Test::a' with 'const' type 'const int'"错误

       在C++中,const成员变量不能在类定义处初始化,只能通过构造函数初始化列表进行,并且必须有构造函数。

         Test():a(0)

         {

         }


阅读(994) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~