静态矢量调整大小

发布于 2025-01-02 10:58:18 字数 586 浏览 0 评论 0原文

我想在类中创建一个静态向量,并且想在创建向量时调整它们的大小。我试图在构造函数或主函数中执行此操作。但我无法让它发挥作用。问题是我无法以这种方式调用向量类的函数。 这就是我现在所拥有的:

#include <vector>

using namespace std;

class test
{
public:
    static vector<int> testvec;
    test();
};

test::test() //Not static
{
    test::testvec.resize(0);    //Try 1
}

vector<int> test::testvec.resize(0); //Try 2

int main()
{
    test::testvec.resize(0); //Try 3
    test testclass;


    system("pause");
    return false;

}

我需要处理每个对象中向量的所有数据,这就是为什么我想使向量静态。

有人可以帮我解决这个问题吗? 谢谢!

编辑:语法。我尝试过的每种方法都会出现编译错误。

I want to make a static vector in a class and I want to resize the vectors when they are created. I'm trying to do this in the constructor or in the main function. But I can't get it to work. The problem is that I can't call a function of the vector class on this way.
This is what I have now:

#include <vector>

using namespace std;

class test
{
public:
    static vector<int> testvec;
    test();
};

test::test() //Not static
{
    test::testvec.resize(0);    //Try 1
}

vector<int> test::testvec.resize(0); //Try 2

int main()
{
    test::testvec.resize(0); //Try 3
    test testclass;


    system("pause");
    return false;

}

I need to handle all the data on the vector in every object, that is why I want to make the vector static.

Can someone help me with this?
Thanks!

Edit: grammer. Every method that I have tried gives a compile error.

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

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

发布评论

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

评论(2

若沐 2025-01-09 10:58:18

当您声明静态成员属性时,您还需要定义它:

class test {
public:
   static std::vector<int> v; // declaration
};
std::vector<int> test::v; // definition, note: no `static` here

您可以选择在构造函数中使用大小,这将避免需要调整大小:

std::vector<int> test::v( 10 ); // definition, create it with size==10

但您仍然可以从 main 调用调整大小 如果您愿意:

int main() { 
   test::v.resize( 20 );
}

When you declare a static member attribute you also need to define it:

class test {
public:
   static std::vector<int> v; // declaration
};
std::vector<int> test::v; // definition, note: no `static` here

You can optionally use a size to the constructor, which would avoid the need to resize:

std::vector<int> test::v( 10 ); // definition, create it with size==10

But you can still call resize from main if you prefer:

int main() { 
   test::v.resize( 20 );
}
够钟 2025-01-09 10:58:18

您需要在实现文件中定义静态成员。

就像在 main.cpp 中一样:

vector<int> Test::testvec;

int main() {
 ...
}

You need to define static members in the implementation file.

like in main.cpp:

vector<int> Test::testvec;

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