您正在寻求的是一个称为反射的原则。不幸的是,C/C++ 不提供此功能,并且在 C++ 对象中实现它会非常复杂(如果可能的话)。
如果需要此功能,我建议查看另一种支持此类元编程功能的语言。在其他一些语言中,做这件事是微不足道的。例如,在 Ruby 中,您可以说:
class Myclass
def initialize
end
def a
end
def b
end
end
x = Myclass.new
x.methods
=> ["inspect", "b", "clone", "taguri", "public_methods", "display", "instance_va
riable_defined?", "equal?", "freeze", "taguri=", "methods", "respond_to?", "dup"
, "instance_variables", "to_yaml_style", "__id__", "method", "eql?", "id", "sing
leton_methods", "send", "taint", "frozen?", "instance_variable_get", "__send__",
"instance_of?", "to_a", "type", "to_yaml_properties", "protected_methods", "obj
ect_id", "instance_eval", "==", "===", "instance_variable_set", "to_yaml", "kind
_of?", "extend", "to_s", "a", "hash", "class", "tainted?", "=~", "private_method
s", "nil?", "untaint", "is_a?"]
这将列出与对象关联的所有成员函数(在这种情况下,其中许多是自动生成的)。对于实例变量等也可以这样做。许多其他语言都提供这些类型的功能。
如果此功能对您所做的工作至关重要,那么我建议您重新检查您选择的编程语言,因为您似乎想要在比 C/C++ 通常设计的更高级别上工作。可以通过使用某种对象/类生成器模式将这种东西硬塞到 C++ 中,但编写或使用生成的类并非易事。