我实际上是想在一个静态函数中使用一个指针,它和我试图在指针中使用的函数在同一个类中。实际上,我被要求这样使用这个类:
class Factory {
public:
Factory() = default;
~Factory() = default;
static IOperand* createOperand(eOperandType type, const std::string& value);
private:
IOperand* createInt8(const std::string& value);
IOperand* createInt16(const std::string& value);
IOperand* createInt32(const std::string& value);
IOperand* createFloat(const std::string& value);
IOperand* createDouble(const std::string& value);
IOperand* createBigDecimal(const std::string& value);
};
如果这个函数不是静态的,我会这样做:
IOperand* Factory::createOperand(eOperandType type, const std::string& value)
{
IOperand* (Factory::*ptr[6])(const std::string&) = {
&Factory::createInt8,
&Factory::createInt16,
&Factory::createInt32,
&Factory::createFloat,
&Factory::createDouble,
&Factory::createBigDecimal
};
return (*this.*ptr[type])(value);
}
ps: eOperandType只是一个枚举
发布于 2021-07-13 12:39:18
无论在何处使用成员函数指针调用方法,都需要一个对象来执行此操作。在你的“如果这个函数不是静态的,这就是我该怎么做”版本中,你在当前对象this
上调用方法。在静态方法中,您需要一个Factory
类型的不同对象,因为静态方法中没有this
。我怀疑实际上Factory
的所有方法都应该是static
的,尽管不涉及到这一点,但您可以这样做:
struct IOperand {};
class Factory {
public:
Factory() = default;
~Factory() = default;
static IOperand* createOperand(size_t type, const std::string& value) {
Factory f;
IOperand* (Factory::*ptr[6])(const std::string&) = {
&Factory::createInt8,
&Factory::createInt16,
&Factory::createInt32,
&Factory::createFloat,
&Factory::createDouble,
&Factory::createBigDecimal
};
return (f.*ptr[type])(value);
}
private:
IOperand* createInt8(const std::string& value);
IOperand* createInt16(const std::string& value);
IOperand* createInt32(const std::string& value);
IOperand* createFloat(const std::string& value);
IOperand* createDouble(const std::string& value);
IOperand* createBigDecimal(const std::string& value);
};
发布于 2021-07-13 12:35:38
您需要知道应该在何处调用其成员函数的对象。
你如何知道它并不重要,关键是你必须以某种形式或方式知道它。可能会将指向对象的指针作为附加参数传递:
IOperand* Factory::createOperand(Factory *obj, eOperandType type, const std::string& value)
{
IOperand* (Factory::*ptr[6])(const std::string&) = {
&Factory::createInt8,
&Factory::createInt16,
&Factory::createInt32,
&Factory::createFloat,
&Factory::createDouble,
&Factory::createBigDecimal
};
return ((*obj).*ptr[type])(value);
}
或者,可能是传入了对对象的引用,而不是指针(导致对代码的轻微调整),或者可能对象位于完全不同的位置。也许createOperand()
会调用其他函数,返回指向其类实例的指针或引用,但重点是成员函数不能由其自身调用。调用其成员函数的对象是必需的。这就是成员函数的含义,以及它与普通函数的区别。
附言:这一切是否都在“静态成员函数中”并不重要。这不是一个因素。唯一的因素是,在非静态成员中,您始终将this
作为可用对象。但是没有法律要求你通过指针来调用this
的成员,如果你在某个地方有同一个类的其他实例,你可以调用它的成员函数,而不是this
one的成员函数。
发布于 2021-07-13 13:16:31
感谢大家的回答,我现在对这个主题和我的项目工作有了更好的理解。
https://stackoverflow.com/questions/68362450
复制相似问题