如何初始化和使用静态结构

时间:2016-12-30 04:19:18

标签: c++ opencv

我在类中定义了一个静态结构。但它导致错误为错误

  

错误LNK1120:1个未解析的外部

我的头文件

class CornerCapturer{
    static struct configValues
    {
        int block;
        int k_size;
        int thre;
        double k;
        configValues() :block(2), k_size(3), thre(200), k(0.04){}
    }configuration;
public:
    void captureCorners(Mat frame);
}

我的cpp文件

void CornerCapturer::captureCorners(Mat frame){

    int y= CornerCapturer::configuration.thre;
}

请帮帮我

2 个答案:

答案 0 :(得分:4)

将此添加到您的cpp文件中; 实例化静态结构:

CornerCapturer::configValues CornerCapturer::configuration;

并且不要忘记课程的;后的}

答案 1 :(得分:0)

静态成员变量需要公开。您当前拥有它的方式隐式使结构变为私有。我运行了一些测试,ASH说的是正确的,你必须在全局范围内实例化结构,但你不能用私有成员做到这一点。就个人而言,我得到了范围错误:

  

'配置'是“Someclass'

的私人会员

只有在我将结构体公开之后:才进行编译而没有错误。

#include <iostream>

class Someclass 
{
public:       
    static struct info 
    {
        int a;
        int b;
        int c;
        info() : a(0), b(0), c(0){}

    } configuration;

    void captureCorners(int frame);
};

struct Someclass::info Someclass::configuration;

void Someclass::captureCorners(int frame) 
{
    configuration.c = frame;
}

int main ()
{
    Someclass firstclass;
    Someclass secondclass;

    Someclass::configuration.a = 10;
    firstclass.configuration.b = 8;
    secondclass.configuration.c = 3;

    using namespace std;


    cout << "First Class a = " << firstclass.configuration.a << "\n";
    cout << "First Class b = " << firstclass.configuration.b << "\n";
    cout << "First Class c = " << firstclass.configuration.c << "\n";

    cout << "Second Class a = " << secondclass.configuration.a << "\n";
    cout << "Second Class b = " << secondclass.configuration.b << "\n";
    cout << "Second Class c = " << secondclass.configuration.c << "\n";

    cout << "Everyclass a = " << Someclass::configuration.a << "\n";
    cout << "Everyclass b = " << Someclass::configuration.b << "\n";
    cout << "Everyclass c = " << Someclass::configuration.c << "\n";

}