Car*_*org 18 c++ overloading pointer-to-member
我正在尝试获取指向特定版本的重载成员函数的指针.这是一个例子:
class C
{
bool f(int) { ... }
bool f(double) { ... }
bool example()
{
// I want to get the "double" version.
typedef bool (C::*MemberFunctionType)(double);
MemberFunctionType pointer = &C::f; // <- Visual C++ complains
}
};
Run Code Online (Sandbox Code Playgroud)
错误消息是"错误C2440:'初始化':无法从'重载函数'转换为'MemberFunctionType'"
如果f没有重载,这可以工作,但不是在上面的例子中.有什么建议吗?
请注意,上面的代码并没有反映我的现实世界问题,那就是我忘记了一个"const" - 这就是被接受的答案所指出的.不过,我会留下问题,因为我觉得问题可能发生在其他人身上.
Joh*_*itb 27
好吧,我会回答我的评论,因此可以接受.问题在于constness:
class C
{
bool f(int) { ... }
bool f(double) const { ... }
bool example()
{
// I want to get the "double" version.
typedef bool (C::*MemberFunctionType)(double) const; // const required!
MemberFunctionType pointer = &C::f;
}
};
Run Code Online (Sandbox Code Playgroud)
澄清:
最初的问题不包含这个问题const.我在评论中做了一个疯狂的猜测,他是否可能f在真实代码中成为const成员函数(因为在更早的迭代中,它发现了另一件事遗传/与现实代码不同:p).他实际上有一个const成员函数,并告诉我我应该发布这个作为答案.
| 归档时间: |
|
| 查看次数: |
10022 次 |
| 最近记录: |