我试图使用同一类的另一个成员进行数组成员

发布于 2025-02-04 16:04:35 字数 363 浏览 1 评论 0原文

我的代码还有更多,但是我卡住的地方是,在运行此代码时,它说对非静态成员“ A”的使用无效。这种方式是无效的还是我的代码有问题?

include <iostream>
using namespace std;

class equation{
    public :
    int a;
    int arr[a][2];
    void seta(int r){
        a = r;
    }
    void setcoef(equation c){
        for(int i = 0; i<c.a; i++){
            cin>>arr[i][1];
        }
    }

There is more to my code but where I'm stuck is that while I run this code it says INVALID USE OF NON STATIC MEMBER 'a'. Is this way invalid or is there something wrong with my code?

include <iostream>
using namespace std;

class equation{
    public :
    int a;
    int arr[a][2];
    void seta(int r){
        a = r;
    }
    void setcoef(equation c){
        for(int i = 0; i<c.a; i++){
            cin>>arr[i][1];
        }
    }

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

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

发布评论

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

评论(1

巷雨优美回忆 2025-02-11 16:04:35

问题是,在标准C ++中,数组的大小必须为编译时间常数,但是由于a是非静态数据成员需要使用一个对象。换句话说,我们需要,该在编译时不可用,而是在运行时可用,因此我们会得到上述错误,说:

INVALID USE OF NON STATIC MEMBER 'a'.

solve 您可以使a <a < /code> a constexpr static数据成员如下所示。这是因为使用静态数据成员不需要类对象(因此指针)。

struct equation
{
    constexpr static int a = 34;
    int arr[a][2];
};

但是,使用静态只会使所有对象的常见,我希望每个对象具有不同的数组大小,我想将其作为输入

您可以使用std :: vector :: vector如下所示:

class equation
{
  std::vector<std::vector<int>> arr;  
  public:
  //constructor that uses constructor initializer list to initialize arr  
  equation(std::size_t row, std::size_t col): arr(row, std::vector<int>(col))
  {
      
  }
};
int main()
{
    equation e(3,4);
    return 0;
}

The problem is that in standard C++ the size of an array must be a compile time constant but since a is a non-static data member it requires an object to be used on. In other words we need this which is available not at compile time but at runtime and hence we get the mentioned error saying:

INVALID USE OF NON STATIC MEMBER 'a'.

To solve this you can make a a constexpr static data member as shown below. This works because using a static data member doesn't require a class object(and hence this pointer).

struct equation
{
    constexpr static int a = 34;
    int arr[a][2];
};

But using static would just make it common for all objects, I want each object to have a different array size, that I want to take as input

You can use std::vector as shown below:

class equation
{
  std::vector<std::vector<int>> arr;  
  public:
  //constructor that uses constructor initializer list to initialize arr  
  equation(std::size_t row, std::size_t col): arr(row, std::vector<int>(col))
  {
      
  }
};
int main()
{
    equation e(3,4);
    return 0;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文