简体   繁体   English

实例化对象时的 C++ 纯虚函数实现

[英]C++ pure virtual function implementation upon instantiating object

I'm not sure if this has already been answered somewhere or if what I'm asking is feasible.我不确定这是否已经在某处得到了回答,或者我所问的是否可行。 I'm not so familiar with C++ and OOP in general so forgive me if I'm asking something too obvious, as my mind is a bit stuck right now.我对 C++ 和 OOP 不太熟悉,所以如果我问的东西太明显了,请原谅我,因为我现在脑子有点卡住了。 Anyway, what I want to deal with is:无论如何,我要处理的是:

I'm using a framework that handles some callbacks from an app.我正在使用一个框架来处理来自应用程序的一些回调。 The API has a class for these events and the callback function as pure virtual function. API 有一个类用于这些事件和回调函数作为纯虚函数。 For example:例如:

class A {
public:
    A(){};
    ~A(){};
    virtual void myCallback(){} = 0 
};

In my code I'm implementing this callback and I have something like:在我的代码中,我正在实现这个回调,我有类似的东西:

class B : A {
public:
    B(){
        std::cout<<"I'm a ClassB object";
    };
    ~B(){};
    void myCallback(){
        std::cout<<"Hello callback";
    };
};

Now in my main suppose that I'm having something like that:现在我主要假设我有这样的事情:

int main(){
    int x=1;
    B objB;
    //Do some stuff for a while
    return 1;
}

I can see upon instantiating the B object the "I'm a ClassB object" message and I can see upon firing the event the "Hello callback" message.我可以在实例化 B 对象时看到“我是 ClassB 对象”消息,在触发事件时我可以看到“Hello 回调”消息。 So what I'm asking here is how I can get inside my callback the value of "x" coming from main ?所以我在这里要问的是如何在我的回调中获取来自 main 的“x”的值? Can I re-implement the callback inside the main somehow?我可以以某种方式在 main 中重新实现回调吗? Do you think that my approach on this is correct ?你认为我的做法正确吗? What I want is to implement pure virtual callback function inside my main by having an object of class B. Or even to somehow get the value of x inside the myCallback function.我想要的是通过拥有一个类 B 的对象在我的 main 中实现纯虚拟回调函数。或者甚至以某种方式在 myCallback 函数中获取 x 的值。 I'm not sure if I'm clear enough or if I messed anything up我不确定我是否足够清楚,或者我是否搞砸了什么

If I understand the question, what you want is usually called a closure .如果我理解这个问题,你想要的通常称为闭包 You want myCallback to know the value of x inside main.您希望myCallback知道 main 中 x 的值。 There are several ways of doing this, the most straightforward will look something like following:有几种方法可以做到这一点,最直接的将如下所示:

class B : public A {
public:
    B(int x) x(x) {
        std::cout<<"I'm a ClassB object";
    }

    ~B() = default;

    void myCallback() {
        std::cout << "Hello callback, x is " << x << "\n";
    }
private:
    int x;
};

int main() {
    int x = 1;
    B objB(x);
    //Do some stuff for a while
    return 0;
}

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

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