【问题标题】:Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript - C++数组下标的无效类型“<未解析的重载函数类型> [int]” - C++
【发布时间】:2015-04-16 15:41:20
【问题描述】:

当我尝试将数字保存到我的向量中时出现此错误...

Invalid types ‘<unresolved overloaded function type>[int]’ for array subscript

代码是:

class Elemento{
private:
    int Nodo;

public:
         Elemento(){};
         ~Elemento(){};
    void SetNumero(int x)    {  Nodo = x;  };
    int  GetNumero()         {  return Nodo; };
};    


class MagicSquare{
private:
    int    N;                             
    int    Possibili_N;                  
    int    Magic_Constant;                

    vector<Elemento> Square(int Possibili_N);    

public:
    MagicSquare()                   {    };
    ~MagicSquare()                  {    };

    void  Set_N(int x)              { N = x; };
    void  Set_PossibiliN(int x)     { Possibili_N = x; };
    void  Set_MagicConstant(int x)  { Magic_Constant = x; };

    . . .

    void SetSquare(int i, int x)    { Square[i].SetNumero(x); }; // got error here
    int  GetSquare(int i)           { return Square[i].GetNumero(); }; // got error here
};

每当我使用 Square[i].method() 时都会出错...

我调用了一个方法来传递 Square 中的索引和要放入 Elemento-&gt;Nodo 的值,但我必须使用公共方法来访问私有 Nodo。与 GET 相同。我想获取显示它的值。

【问题讨论】:

    标签: c++ function vector


    【解决方案1】:

    您似乎已将 Square 声明为函数,而不是变量。

    相反,声明vector&lt;Elemento&gt; Square; 并在构造函数中对其进行初始化。

    【讨论】:

    • 那么,如何在构造函数中初始化它呢?我必须在 N、Possible_N 和 MagicCostant 之前计算,然后我可以对向量进行标注...
    • @FedericoCuozzo 如果你必须先计算一些东西,你可以使用vector::resize
    【解决方案2】:

    您将Square 声明为函数,而不是变量。所以Square[i] 无效。
    改变

    vector<Elemento> Square(int Possibili_N); 
    

    vector<Elemento> Square;
    

    或调用它使用

    Square(i)
    

    如果它实际上是一个函数。

    如果将其更改为变量,则需要确保正确初始化它,最好在构造函数中。

    【讨论】:

      【解决方案3】:

      您的线路vector&lt;Elemento&gt; Square(int Possibili_N); 被称为C++ most vexing parse

      您不是按照预期声明一个成员变量,而是声明一个接受int 并返回一个向量的函数。

      相反,在构造函数初始化列表中设置成员向量(和所有其他成员变量):

      class MagicSquare{
      private:
          int N;
          int Possibili_N;
          int Magic_Constant;
          vector<Elemento> Square;
      
      public:
          MagicSquare( int n, int p, int m ) :
              N( n ),
              Possibili_N( p ),
              Magic_Constant( m ),
              Square( p ) {
          }
      ...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-26
        • 2012-09-07
        • 1970-01-01
        • 2021-05-04
        • 1970-01-01
        • 1970-01-01
        • 2022-01-05
        相关资源
        最近更新 更多