继承成员函数指针
Inheriting member function pointers
我在网上看到了这段代码,我想知道它是如何实现的。 由于成员函数指针不能分配给基类的成员函数指针,我很好奇派生类的成员函数的指针存储在哪里以及如何存储。
这是带有测试声明的头文件
#ifndef TestStudent_h
#define TestStudent_h
#include <iostream>
#include <string>
// Note 1
#include "TestCase.h"
#include "TestSuite.h"
#include "TestCaller.h"
#include "TestRunner.h"
#include "Student.h"
class StudentTestCase : public TestCase { // Note 2
public:
// constructor - Note 3
StudentTestCase(std::string name) : TestCase(name) {}
// method to test the constructor
void testConstructor();
// method to test the assigning and retrieval of grades
void testAssignAndRetrieveGrades();
// method to create a suite of tests
static Test *suite ();
};
#endif
这是将成员函数添加到某种列表中的函数的实现
// method to create a suite of tests - Note 7
Test *StudentTestCase::suite () {
TestSuite *testSuite = new TestSuite ("StudentTestCase");
// add the tests
testSuite->addTest (new TestCaller
("testConstructor", &StudentTestCase::testConstructor));
testSuite->addTest (new TestCaller
("testAssignAndRetrieveGrades",
&StudentTestCase::testAssignAndRetrieveGrades));
return testSuite;
}
我想知道成员函数存储在什么数据类型中,因为它们不能存储在基类已知的任何函数指针类型中。 此外,存储它们的位置必须知道定义这些对象的类的类型,因为调用这些对象的任何实体都需要将这些函数与该类型的对象"链接"起来,对吗? 特别是在此函数中,TestCaller
如何知道如何调用添加到其中的成员函数?
我的猜测是TestCaller
有一个看起来像
template<class Callee>
TestCaller(
const std::string &description,
void (Callee::*test_method)());
请注意:
在此构造函数的主体中(即,当它被实例化时),
Callee
的类型是已知的。TestCaller
本身必须以一种不"知道"Callee
的方式存储test_method
,因为它本身不是由Callee
参数化的模板类(事实上,可能不止一个Callee
)。
所以这是类型擦除的经典案例。有许多库可以做到这一点(例如,boost::TypeErasure
或boost::any
)。
这个想法是TestCaller
存储(可能间接)指向非模板基类的指针。存在派生类的模板化版本。在此模板化 ctor 中,将实例化派生类,并动态分配此类型的对象。但是,存储的内容是指向非模板基类的指针。
相关文章:
- 如何正确编写指针函数声明?
- C++常规指针函数或模板
- 如何重新定义 C++ 指针函数?
- C++ 指向其他类函数的指针函数
- 指针到指针函数参数
- 将指向成员的指针函数传递到模板中
- C++ 在 none 常量指针函数中返回一个常量指针
- 如何使用指针函数编写/读取数组
- 是C 中的函数指针函数对象
- 如何从另一个类调用指向成员的指针函数
- 如何声明采用指向成员的指针函数的函数
- 如何构造一个以可变参数指针函数作为成员的类?
- c 通过值或指针函数语法
- 将typedef方法作为指针函数传递
- 从 Main 中的双指针函数打印出指针数组
- strcpy 对指针函数的引用
- 这是否仍然声明一种指针函数的别名?
- 将指向成员的指针函数与 std::shared_ptr 结合使用
- 'Incomplete type' 为标准::函数声明指向成员的指针函数模板参数时出错
- 从注入进程的 DLL 调用函数并更改指针函数的地址