简体   繁体   English

在派生类的对象上使用指向基类的成员函数的指针

[英]Using pointer to member function of a base class on object of derived class

Consider following code snippet: 请考虑以下代码段:

struct Base {
    std::string foo () const { std::cout << "Base::foo()\n"; return "X"; }
};

struct Der : Base {};

struct Ptr : std::integral_constant<std::string (Base:: *) () const, &Base::foo> {};

and usage is like this: 和用法是这样的:

Der der;
std::string s = (der.*Ptr::value) ();
std::cout << s << "\n";

Output is as desired: 输出符合要求:

Base::foo()
X

Everything seems to be fine. 一切似乎都很好。

My question is: Is this code correct? 我的问题是:这段代码是否正确? Or am I stepping on the land of undefined behavior? 还是我踩着未定义的行为? Can I use pointer to member function of a base class on object of derived class directly? 我可以直接使用指向派生类对象的基类成员函数的指针吗?

Roughly speaking, the member belongs to the suboject and thus you must use its type to identify it. 粗略地说,该成员属于子对象,因此您必须使用其类型来识别它。 Perfectly fine indeed. 确实非常好。

The other way around doesn't even compile actually: 反过来甚至没有实际编译:

struct Ptr : std::integral_constant<std::string (Der:: *) () const, &Der::foo> {};

The error is pretty clear: 错误很明显:

error: could not convert template argument '&Base::foo' from '[...] (Base:: )() const}' to '[...] (Der:: )() const' 错误:无法将模板参数'&Base :: foo'从'[...](Base :: )()const}'转换为'[...](Der :: )()const'

Where I used [...] to reduce it a bit. 我使用[...]减少它的地方。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用基类函数指针访问派生类成员函数 - Using base class function pointer to access derived class member function 为什么我可以通过指向派生对象的基类指针访问派生的私有成员函数? - Why can I access a derived private member function via a base class pointer to a derived object? C ++:在另一个派生类的对象的基本指针上调用(派生的)成员函数 - C++: call (derived's) member function on base pointer of a different derived class's object 如何注册派生的 class 成员 function 指针与基数 class - How to register a derived class member function pointer with a base class 函数在派生类中但不在基类中,指向基类的指针--&gt;“不是成员”错误 - function in derived but not in base class, pointer to base --> "not a member" error 指向派生 class 中的基 class 作为成员变量的指针 - Pointer to base class in derived class as a member variable 使用派生 class 成员 function 访问基 class 的私有成员 - Accessing private member of base class using derived class member function 成员函数指针转换,从派生类到基类 - Member function pointer cast, from Derived to Base class 如何通过派生的指针在基类中调用模板成员函数 - How to call template member function in the base class by the derived pointer C ++:在不同类的派生对象的基本指针上调用静态成员函数 - C++: call static member function on base pointer of different class's derived object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM