我的问题是关于成员函数指针。这里有一个示例代码:类C继承foo自A和bar自B. 我预计两者&C::foo和&C::bar都是相同的类型void (C::*)(),但实际上它们是不同的类型,一种是void(A::*)()
,另一种是void(B::*)()。我使用 gdb ptype 命令来检查数据类型。
我的问题是:这种行为是由 C++ 标准定义的吗?这个设计决策的基本原理是什么?
#include <type_traits>
#include <iostream>
struct A {
void foo() {
std::cout << this << std::endl;
}
int a;
};
struct B {
void bar() {
std::cout << this << std::endl;
}
int b;
};
struct C : public A, B { };
int main() {
auto p1 = &C::foo; // p1 is void (A::*)();
auto p2 = &C::bar; // p2 is void (B::*)();
auto p3 = &A::foo; // p3 is void (A::*)();
bool b1 = std::is_same<decltype(p1), decltype(p2)>::value;
bool b2 = std::is_same<decltype(p1), decltype(p3)>::value;
std::cout << b1 << std::endl; // false
std::cout << b2 << std::endl; // true
return 0;
}