当按下按钮时,我不想在该按钮所在的类中而是在另一个类中处理该函数调用。因此,以下是我要实现的代码:
#include <vector>
#include <unordered_map>
#include <iostream>
std::vector<int> groupNumbers(const std::vector<int> &input)
{
std::vector<int> grouped;
std::unordered_map<int, int> counts;
for (auto &x: input)
{
++counts[x];
}
for (auto &x: counts)
{
grouped.insert(grouped.end(), x.second, x.first);
}
return grouped;
}
// example
int main()
{
std::vector<int> test{1,2,3,4,3,2,3,2,3,4,1,2,3,2,3,4,3,2};
std::vector<int> result(groupNumbers(test));
for (auto &x: result)
{
std::cout << x << std::endl;
}
return 0;
}
请让我知道这是如何实现的,并非常感谢!
答案 0 :(得分:1)
注意:我编辑了回复,因为我无法正确理解您的问题。
在python中,您可以将函数作为参数传递:
class TestButton:
def __init__(self, root, command):
self.testButton = Button(root, text ="Test Button", command = command).grid(row = 11, column = 0)
#testButtonPressed is called in the TestButton class.
class TestClass:
#The testButtonPressed function is handled in the TestClass.
def testButtonPressed(self):
print "Button is pressed!"
TestButton(root, TestClass().testButtonPressed)
答案 1 :(得分:0)
如果已经定义了该类,并且您要传递的函数是静态的,则应该能够执行以下操作:
class TestClass:
def testButtonPressed(self):
print "Button is pressed!"
class TestButton:
def __init__(self, root):
self.testButton = Button(root, text="Test Button", command=TestClass.testButtonPressed).grid(row=11, column=0)
记住::将函数作为参数传递时,需要删除括号“()”。如果不这样做,您将传递函数返回的内容,而不是函数本身。
。
如果要传递的函数不是静态的(需要在类的实例中调用),则必须具有对该实例的引用:
class TestClass:
def __init__(self):
self.message = "Button is pressed!"
def testButtonPressed(self):
print self.message
class TestButton:
def __init__(self, root):
instance = TestClass()
self.testButton = Button(root, text="Test Button", command=instance.testButtonPressed).grid(row=11, column=0)
,或者,如果实例不在类的范围之内:
instance = TestClass()
class TestButton:
def __init__(self, root, reference):
self.testButton = Button(root, text="Test Button", command=reference.testButtonPressed).grid(row=11, column=0)
test = TestButton(root, instance)
注意:通常可以通过使用“ self”参数来标识非静态方法,例如:
def function(self)