【发布时间】:2016-06-24 19:46:19
【问题描述】:
我在网上看到了这段代码,想知道它是如何实现的。由于不能将成员函数指针分配给基类的成员函数指针,我很好奇派生类成员函数的指针存储在哪里以及如何存储。
这是带有测试声明的头文件
#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如何知道如何调用添加到它的成员函数?
【问题讨论】:
-
@n.m.但是它们需要存储在某个地方吗?
-
不涉及基类,TestSuite是。
-
对不起,我想我不明白你在问什么。成员函数不会“存储”在任何地方,它们只是。成员函数指针存储在它们的社会化数据类型中。它们是没有任何结构的原始数据类型。
-
@kfsone 那么TestSuite 怎么知道如何调用这些函数呢?它们必须与
StudentTestCase类型的对象链接,对吗? -
@Downvoter 为什么投反对票?
标签: c++ pointers c++11 function-pointers member-function-pointers