繁体   English   中英

未定义对 C++ 中 Class 结构向量的 static 向量的引用 [暂停]

[英]Undefined reference to static vector of structure in a Class in C++ [on hold]

我想在 Class 中声明结构的 static 向量,然后在 class 函数中使用它。 但它一直给我错误:

undefined reference

首先,我尝试了一个不使用结构的简单代码。 以下代码运行没有任何错误:

#include <iostream>
#include <vector>
using namespace std;

class CACHE
{
    public:
        static vector<int> gtt;

        CACHE(int index, int value){
            gtt[index]=value;
        }

        void show_gtt(){
            for(int i=0; i<4; i++){
                cout<<gtt[i]<<'\n';
            }
            cout<<'\n';
        }
};

//Initializing 4 values
vector<int> CACHE::gtt = vector<int>(4);

int main(){

    CACHE L1(1, 78);
    L1.show_gtt();
    CACHE L2(2, 55);
    L2.show_gtt();

    return 0;
}

我知道我最多可以有 4 个对象,因此在函数和初始化中使用“4”。 output如下:

0
78
0
0

0
78
55
0

现在,我尝试使用相同的概念,但使用如下结构:

#include <iostream>
#include <vector>
using namespace std;

struct gtt_struct
{
    static int  x;
    static int  y;
};

class CACHE
{
    public:
        static vector<gtt_struct> gtt;

        CACHE(int index, int value_1, int value_2){
            gtt[index].x=value_1;
            gtt[index].x=value_2;
        }

        void show_gtt(){
            for(int i=0; i<4; i++){
                cout<<"["<<gtt[i].x<<", "<<gtt[i].y<<"]\n";
            }
            cout<<'\n';
        }
};

//Initializing 4 values
vector<gtt_struct> CACHE::gtt = vector<gtt_struct>(4);

int main(){

    CACHE L1(1, 78, 33);
    L1.show_gtt();
    CACHE L2(2, 55, 49);
    L2.show_gtt();

    return 0;
}

上面的代码给了我以下编译错误:

/tmp/ccijWpnu.o: In function `CACHE::CACHE(int, int, int)':
test_1.cpp:(.text._ZN5CACHEC2Eiii[_ZN5CACHEC5Eiii]+0x2e): undefined reference to `gtt_struct::x'
test_1.cpp:(.text._ZN5CACHEC2Eiii[_ZN5CACHEC5Eiii]+0x4b): undefined reference to `gtt_struct::x'
/tmp/ccijWpnu.o: In function `CACHE::show_gtt()':
test_1.cpp:(.text._ZN5CACHE8show_gttEv[_ZN5CACHE8show_gttEv]+0x4a): undefined reference to `gtt_struct::x'
test_1.cpp:(.text._ZN5CACHE8show_gttEv[_ZN5CACHE8show_gttEv]+0x80): undefined reference to `gtt_struct::y'
collect2: error: ld returned 1 exit status

我想我已经遵循了其他帖子中提到的初始化指南。 但似乎结构语法导致了这个问题。 语法gtt[index].x不正确吗? 还是其他一些 C++ 概念问题?

您定义了 x 和 y static。 所以像这样使用它们:gtt[index]::x, ::y

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM