ClassB中有一个静态函数,是ClassA的回调函数show,但是show函数需要用到ClassB中的非静态变量,该如何操作?
#include <iostream>
#include <functional>
#include <windows.h>
class A
{
using CallBack = std::function<void(int a)>;
public:
void SetCallBack(const CallBack& pf) {
callback = pf;
}
void run() {
int i = 0;
while (1)
{
callback(i++);
Sleep(1000);
}
}
private:
CallBack callback;
};
class B
{
public:
B() {
m_pthis = this;
m_i = 0;
}
void run(){
m_a.SetCallBack(show);
m_a.run();
}
private:
static B *m_pthis;
static void show(int a) {
std::cout << m_pthis->m_i <<","<< a <<std::endl;
}
int m_i;
A m_a;
};
void main()
{
B b;
b.run();
};
错误 LNK2001 无法解析的外部符号 "private: static class B * B::m_pthis"
static B m_pthis;
static void show(int a) {
std::cout << m_pthis.m_i <<","<< a <<std::endl;
}
这样改下试试
逻辑挺绕, 但是没有问题, 只是语言基本功不扎实.
.
静态成员, 除个别只用于内部使用的常量, 其余均需类内声明, 类外定义.
#include <functional>
#include <iostream>
#include <windows.h>
class A
{
using CallBack = std::function<void(int a)>;
public:
void SetCallBack(const CallBack &pf)
{
callback = pf;
}
void run()
{
int i = 0;
while (true)
{
callback(i++);
Sleep(1000);
}
}
private:
CallBack callback;
};
class B
{
public:
B()
{
m_pthis = this;
m_i = 0;
}
void run()
{
m_a.SetCallBack(show);
m_a.run();
}
private:
static B *m_pthis;
static void show(int a)
{
std::cout << m_pthis->m_i << "," << a << std::endl;
}
int m_i;
A m_a;
};
// 定义
B *B::m_pthis;
auto main() -> int
{
B b;
b.run();
};