我可能在这里要求一些荒谬的东西(我是 c++ 的新手),但我仍然想尝试一下。我试图在接收它的对象的函数中访问类的方法,但与此同时,我想以某种方式不必指定是哪个类,这就是我使用模板的原因。这听起来非常愚蠢,但无论如何,这就是代码:
class Dog;
class Animals{
public:
// initializes all protected variables
Animals(string fam, string gen, string espec, string subespec);
~Animals();
template <class A>
void Eat(A &);
protected:
string family;
string genre;
string especies;
string subespecies;
};
template <class A>
void Animals::Eat(A &obj)
{
// this is where I don't know what I could do.
std::cout << obj.methodOfA();
}
/---
int main()
{
Dog *myDog = new Dog;
myDog->Eat(myDog);
//supposing I had class "Cats"
Cat *myCat = new Cat;
myCat->Eat(myCat);
}
这可能非常愚蠢,所以请随时指出我对答案的愚蠢...如果有人回答过这个问题。 我想要这个是因为我将有许多派生自 Animals 类的类,并且独立于这些类中的哪些,我希望它们能够正确使用此方法。
谢谢。
最佳答案
解决问题的一种方法是将要执行的函数作为第二个参数传递。然后您可以使用 operator.*
或 operator->*
调用该函数。
这看起来像这样:
class Animals {
public:
// initializes all protected variables
Animals(std::string fam, std::string gen, std::string espec, std::string subespec);
~Animals();
template <class A, class Fun>
void Eat(A *&, Fun);
protected:
std::string family;
std::string genre;
std::string especies;
std::string subespecies;
};
template <class A, class Fun>
void Animals::Eat(A *& obj, Fun function)
{
std::cout << ((obj->*function)()).c_str();
}
class Dog : public Animals {
public:
std::string TestFunction() {
return std::string("I am a dog");
}
};
int main() {
Dog *myDog = new Dog;
myDog->Eat(myDog, &Dog::TestFunction);
//...
}
这个程序的输出是:
I am a dog
澄清这一行:
((obj->*function)())
您首先将operator->*
应用于obj
并将成员函数function
的地址传递给它。请注意,您必须在该语句两边加上括号。之后调用它。(()
)。
如果对上面提供的代码有任何疑问,请随时提问。
问候,
飞鸟
关于c++ - 使用模板调用类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36191596/