我想知道为什么该语言允许声明指向成员函数/数据的指针,尽管该成员类型不存在,而且我们知道在编译时,必须知道静态类型,并且在使用之前必须知道类型必须是完整类型除了在如此受限制的情况下使用不完整的类型。
这是我的例子:
struct Foo{
int bar(bool, bool){std::cout << "Foo::bar\n"; return x_;}
int x_ = 10;
void do_it()const{cout << "do_it()\n";}
void do_it(int, bool)const{cout << "do_it(int, bool)\n";};
};
int main(){
int (Foo::* pMemBar)(bool, bool) = &Foo::bar; // ok
(Foo{}.*pMemBar)(0, 0); // ok
int Foo::*pMemX = &Foo::x_;
std::cout << Foo{}.*pMemX << '\n';
std::string (Foo::* pMemFn)(char)const; // why this is allowed?
std::string Foo::* pMemDt = nullptr; // why allowed
}
Run Code Online (Sandbox Code Playgroud)
pMemFn,该指针是指向类的成员函数Foo即const与只有一个参数作为char并返回std::string。但是类中没有这样的版本,Foo正如我们所知,编译器确实知道类的所有成员,那么为什么它允许呢?我知道这个指针还没有被取消引用,因此在这样的声明中没有那个类的对象,编译器只有在使用那种类型的对象取消引用它时才会抱怨,class …