c ++错误。这个指针的概念问题

时间:2014-06-20 04:32:58

标签: c++ pointers this

特别是我的代码中出现错误。 以下是部分错误:

Prefix.cpp: In member function ‘bool Prefix::isRegistered(int) const’:
Prefix.cpp:47:20: error: invalid types ‘int[int]’ for array subscript
Prefix.cpp: In member function ‘bool Prefix::isRegistered(int, const char*)’:
Prefix.cpp:68:15: error: request for member ‘area’ in ‘this’, which is of non-class type ‘Prefix* const’
Prefix.cpp: In function ‘int minNoDigits(int)’:
Prefix.cpp:98:35: error: invalid use of ‘this’ in non-member function
Prefix.cpp:100:10: error: invalid use of ‘this’ in non-member function
Prefix.cpp:103:18: error: invalid use of ‘this’ in non-member function
CODE.cpp: In member function ‘bool EAN::isRegistered(const Prefix&)’:
CODE.cpp:40:34: error: request for member ‘str’ in ‘this’, which is of non-class type ‘EAN* const’
CODE.cpp:62:35: error: request for member ‘str’ in ‘this’, which is of non-class type ‘EAN* const’
CODE.cpp:65:51: error: passing ‘const Prefix’ as ‘this’ argument of ‘bool Prefix::isRegistered(int, const char*)’ discards qualifiers [-fpermissive]
CODE.cpp:81:34: error: request for member ‘str’ in ‘this’, which is of non-class type ‘EAN* const’

cpp文件:

#include <string.h>
using namespace std;
#include "Prefix.h"



//Checks if the area element is valid.
bool Prefix::isRegistered(int area) const
{
   int index;
   bool found=false;

   //Search within the prefix range table to see if area element exists.

   for(index=0; !found && index < no; index++)
   {
      if(this.area[index] == area)
         found = true;
   }

   return found;
}

谢谢!非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

以下错误:

GS1Prefix.cpp: In member function ‘bool Prefix::isRegistered(int) const’:
GS1Prefix.cpp:47:20: error: invalid types ‘int[int]’ for array subscript
GS1Prefix.cpp: In member function ‘bool Prefix::isRegistered(int, const char*)’:
GS1Prefix.cpp:68:15: error: request for member ‘area’ in ‘this’, which is of non-class type ‘Prefix* const’

和EAN.cpp中的错误是因为你写了this.。那是一个错误。 this是一个指针,因此您应该使用this->来访问成员。 .用于通过对象(而不是指针)访问成员。

错误消息中非常清楚地解释了其他错误:

GS1Prefix.cpp: In function ‘int minNoDigits(int)’:
GS1Prefix.cpp:98:35: error: invalid use of ‘this’ in non-member function
GS1Prefix.cpp:100:10: error: invalid use of ‘this’ in non-member function
GS1Prefix.cpp:103:18: error: invalid use of ‘this’ in non-member function

this仅在成员函数中定义。它是指向调用成员函数的对象的指针。由于minNoDigits是一个自由函数,因此没有这样的对象。