C ++类初始化列表和传递函数 [英] C++ class initializing list and passing functions

查看:202
本文介绍了C ++类初始化列表和传递函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的在网上搜索这个,但从来没有想出一个答案。我知道两种方式初始化一个类,其中之一不工作,当我尝试传递一个函数。你能帮我明白为什么会这样吗?我应该使用什么方法?先感谢!

I really searched the web for this but never came up with an answer. I know two ways of initializing a class and one of them doesn't work when I try to pass a function. Can you help me understand why this happens? And what method should I use? Thanks in advance!

void func(int i){
    cout << "GG " << i; 
}

class ac{
public:
    int a;
    function<void()> sh = bind(&func, a);

    /*ac (int i){   This does not work
        a = i;
    }*/

    ac (int i) : a(i) {};   // but this does

    void go (){
        sh();
    }
};

int main() {
    ac ac1(5);
    ac1.go();
    return 0;
}

编辑:感谢所有的回应, 。看起来第一个例子的输出是一些随机垃圾,我不确定这是为什么我犹豫细节输出。

Thanks for all the responses, this was a lot quicker than I thought. It seems like the output of the first example was some random garbage, I wasn't sure that's why I hesitated to detail the output.

推荐答案

当你在类初始化时,只是一个简单的手,由构造函数做,如果你不自己做。这意味着

When you do in class initialization it is just a short hand to have that done by the constructor if you do not do it yourself. That means

ac (int i){
    a = i;
}

成为

ac (int i) : a(garbage), sh(bind(&func, a)){
    a = i;
}

现在我们有一个默认的初始化) a 用于函数,所以我们有垃圾。 a 之前的原因是 sh 是在类中声明的方式,并指示初始化的顺序。

So now we have a default initialized (which in this case means it contains garbage) a being used for the function so we have garbage. The reason a comes before sh is that is the way the declred in the class and that dictates the order of initialization.

第二个示例工作原理是构造函数被视为

The second example works as the constructor is treated as

ac (int i) : a(i), sh(bind(&func, a)){
    a = i;
}

现在当我们绑定 a func a 初始化为实际值。

And now when we bind a to func a is initialized to an actual value.

这篇关于C ++类初始化列表和传递函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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