我在这里读到了几个关于这个主题的问题,这个问题似乎让我感到困惑.我刚刚开始学习C++,我还没有学过模板或运算符重载等等.
现在有一种简单的重载方式
class My {
public:
int get(int);
char get(int);
}
Run Code Online (Sandbox Code Playgroud)
没有模板或奇怪的行为?或者我应该
class My {
public:
int get_int(int);
char get_char(int);
}
Run Code Online (Sandbox Code Playgroud)
?
在Y::test1()非const X::operator void*()中优先于看似更好的匹配,X::operator bool() const- 为什么?标准中描述了这种现象在哪里?
#include <iostream>
struct X {
operator void*() { std::cout << " operator void*()\n"; return nullptr; }
operator bool() const { std::cout << " operator bool()\n"; return true; }
};
struct Y {
X x;
bool test1() { std::cout << "test1()\n"; return x; }
bool test2() const { std::cout << "test2()\n"; return x; }
};
int main() {
Y y;
y.test1();
y.test2();
}
Run Code Online (Sandbox Code Playgroud)
输出:
test1()
operator void*()
test2()
operator bool()
Run Code Online (Sandbox Code Playgroud)