有一个我无法阻止编译的不受欢迎的 C 样式转换。不需要的强制转换执行从某个类的对象到某个其他类的非常量引用的 C 样式转换。类是不相关的。同时,我喜欢支持从同一个类的对象到 const 引用的 C 风格转换。我正在提供一个公共转换运算符来支持理想的演员阵容。在这种情况下,似乎无法阻止不受欢迎的演员。
对非常量引用的转换无法构建(“Sandbox::B::operator Sandbox::A &() ”(在第 30 行声明)不可访问*),不幸的是,转换为 const 引用要么失败(错误:多个从“Sandbox::B”到“const Sandbox::A”的转换函数适用:函数“Sandbox::B::operator const Sandbox::A &()”函数“Sandbox::B::运算符沙箱::A &()" ):
#include <iostream>
#include <string>
#include <cstdlib>
namespace Sandbox {
class A {
public:
A (int i) : _x (i) { }
private:
int _x;
};
class B {
public:
B (const char* m) : _m (m), _a (std::atoi (m)) { }
/*
* This one shall be supported.
*/
operator const A& () …Run Code Online (Sandbox Code Playgroud)