C++ static virtual members?(C++ 静态虚拟成员?)
问题描述
在 C++ 中是否有可能同时具有 static 和 virtual 的成员函数?显然,没有一种直接的方法来做到这一点(static virtual member(); 是一个编译错误),但至少有一种方法可以达到同样的效果吗?
Is it possible in C++ to have a member function that is both static and virtual? Apparently, there isn't a straightforward way to do it (static virtual member(); is a compile error), but is there at least a way to achieve the same effect?
即:
struct Object
{
     struct TypeInformation;
     static virtual const TypeInformation &GetTypeInformation() const;
};
struct SomeObject : public Object
{
     static virtual const TypeInformation &GetTypeInformation() const;
};
在实例 (object->GetTypeInformation()) 和类 (SomeObject::GetTypeInformation) 上使用 ),这对比较很有用,对模板很重要.GetTypeInformation() 是有意义的()
It makes sense to use GetTypeInformation() both on an instance (object->GetTypeInformation()) and on a class (SomeObject::GetTypeInformation()), which can be useful for comparisons and vital for templates.
我能想到的唯一方法是为每个类编写两个函数/一个函数和一个常量,或者使用宏.
The only ways I can think of involves writing two functions / a function and a constant, per class, or use macros.
还有其他解决方案吗?
推荐答案
不,没有办法,因为当你调用 Object::GetTypeInformation() 时会发生什么?它不知道要调用哪个派生类版本,因为没有与之关联的对象.
No, there's no way to do it, since what would happen when you called Object::GetTypeInformation()?  It can't know which derived class version to call since there's no object associated with it.
您必须使其成为非静态虚拟函数才能正常工作;如果您还希望能够在没有对象实例的情况下以非虚拟方式调用特定派生类的版本,则还必须提供第二个冗余静态非虚拟版本.
You'll have to make it a non-static virtual function to work properly; if you also want to be able to call a specific derived class's version non-virtually without an object instance, you'll have to provide a second redunduant static non-virtual version as well.
这篇关于C++ 静态虚拟成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 静态虚拟成员?
 
				
         
 
            
        基础教程推荐
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
    	 
						 
						 
						 
						 
						 
				 
				 
				 
				