指针数组作为函数中的参数

发布于 2024-12-18 01:28:31 字数 435 浏览 0 评论 0原文

我在类中创建此函数,但收到错误:不允许指向不完整类类型的指针。

然而,就我而言,可以声明一个指向抽象类对象的指针数组。之后,您可以在数组中传递派生类的对象。 这段代码的问题出在哪里(Square类是抽象的):

public:
Player(int,int);
void captureSquare(Square* []);

void Player::captureSquare(Square* allSquares[22])
{
  for(int i=0;i<22;i++){
    Square* OnSquare = allSquares[i];
      if(OnSquare->getID==squarePosition){
        capturedSquare = OnSquare;
        break;
 }
}

}

I create this function in a class and I receive error: pointer to incomplete class type is not allowed.

As far as I am concerned however it is possible to declare an array of pointers to an object of an abstract class. After that you can pass objects of the derived class in the array.
Where is the problem with this code (class Square is abstract):

public:
Player(int,int);
void captureSquare(Square* []);

void Player::captureSquare(Square* allSquares[22])
{
  for(int i=0;i<22;i++){
    Square* OnSquare = allSquares[i];
      if(OnSquare->getID==squarePosition){
        capturedSquare = OnSquare;
        break;
 }
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞花火° 2024-12-25 01:28:31

您必须确保当您使用类时(通过取消引用指针),Square 的类定义可见。通常是这样的:

// player.hpp

class Square;

class Player
{
  void captureSquare(Square* []);
};

// player.cpp

#include "player.hpp"
#include "square.hpp"

void Player::captureSquare(Square* allSquares[22])
{
  allSquares[0]->foo();  // need complete class here!
}

You have to make sure that the class definition of Square is visible when you use the class (by dereferencing the pointer). Typically like this:

// player.hpp

class Square;

class Player
{
  void captureSquare(Square* []);
};

// player.cpp

#include "player.hpp"
#include "square.hpp"

void Player::captureSquare(Square* allSquares[22])
{
  allSquares[0]->foo();  // need complete class here!
}
此岸叶落 2024-12-25 01:28:31

抱怨类型不完整的错误通常意味着该类的定义此时不可用。您是否可能在同一文件或包含的文件中的某处有类似 class Square; 的行(没有通常的大括号及其内容)?

如果没有看到更多代码(并且不知道编译器抱怨的是哪一行),则很难说更明确的事情。

An error complaining about an incomplete type usually means that the class's definition is not available at that point. Do you perhaps have a line like class Square; (without the usual curly brackets and their contents) somewhere in the same file or in an included file?

It's hard to say anything more definite without seeing more of your code (and without knowing which line the compiler is complaining about).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文