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

标签 c++ pointers this

我的代码中出现错误,尤其是 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;
}

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

最佳答案

以下错误:

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 是一个自由函数,所以没有这样的对象。

关于C++ 错误。这个指针的概念问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24320008/

相关文章:

pointers - 即使我使用指向某个类型的指针来更新它,我的对象也不会更新

javascript - 数组方法中关于 'thisArg' 的混淆

javascript - 将 js 对象的属性传递到其方法中

C++ 如何强制预取数据缓存? (数组循环)

c++ - 错误,动态分配对象到数组

c++ - TFS 2013 构建如何使工作区文件可编辑?

c - 如何清除传递给 C 函数的 char*?

c++ - 导致非原子撕裂

c++ - 将 std::string 传递给函数 f(**char)

javascript - 维护范围