头文件中的C / C ++私有数组初始化 [英] C/C++ private array initialization in the header file

查看:114
本文介绍了头文件中的C / C ++私有数组初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个叫做Cal的类,它是.cpp和.h对应对象

I have a class called Cal and it's .cpp and .h counterpart

Headerfile有

Headerfile has

class Cal {
    private:
        int wa[2][2];

    public:
        void do_cal();
};

.cpp文件具有

#include "Cal.h"
void Cal::do_cal() {
   print(wa) // where print just itterates and prints the elements in wa
}

我的问题是如何初始化数组 wa ?我似乎无法正常工作。

My question is how do I initialize the array wa ? I just can't seem to get it to work.

我尝试过:

int wa[2][2] = {
                {5,2},
                {7,9}
               };

在头文件中,但是我收到错误消息说我不能这样做,因为它是针对iso..something的。

in the header file but I get errors saying I cant do so as it's against iso..something.

还尝试在构造函数中初始化数组 wa ,但这也没有用。我想念什么?

Tried also to initialize the array wa in the constructor but that didnt work either.. What am I missing ?

谢谢

推荐答案

如果它可以是静态的,则可以初始化在您的.cpp文件中。在类声明中添加static关键字:

If it can be static, you can initialize it in your .cpp file. Add the static keyword in the class declaration:

class Cal {
    private:
        static int wa[2][2];
    public:
        void do_cal();
};

并在.cpp文件的文件范围内添加:

and at file scope in the .cpp file add:

#include "Cal.h"
int Cal::wa[2][2] = { {5,2}, {7,9} };
void Cal::do_cal() {
   print(wa) // where print just itterates and prints the elements in wa
}

如果您从不更改它,那么它将很好地工作(以及使其成为const)。不过,您只会得到与课程的每个实例共享的一个。

If you never change it, this would work well (along with making it const). You only get one that's shared with each instance of your class though.

这篇关于头文件中的C / C ++私有数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆