C++ 使用用户定义的转换运算符隐式转换此
假设我有以下代码:C++ 使用用户定义的转换运算符隐式转换此,c++,type-conversion,implicit-conversion,C++,Type Conversion,Implicit Conversion,假设我有以下代码: class Base { }; class Foo { public: Foo(Base* base) { } }; class BarBase { public: operator Base*() { return base; } private: Base* base; }; class Bar : public BarBase { public: Bar() {
class Base
{
};
class Foo
{
public:
Foo(Base* base)
{
}
};
class BarBase
{
public:
operator Base*()
{
return base;
}
private:
Base* base;
};
class Bar : public BarBase
{
public:
Bar()
{
Foo* foo = new Foo(this);
}
};
代码未能编译,GCC 6.3中出现以下错误:
prog.cpp: In constructor ‘Bar::Bar()’:
prog.cpp:30:26: error: no matching function for call to ‘Foo::Foo(Bar*)’
Foo* foo = new Foo(this);
^
Bar
派生自的BarBase
具有用户定义的转换运算符,用于Base*
。为什么不使用上述转换运算符将此隐式转换为Base*
?您已经正确定义了隐式转换运算符,但是它不适用于指向对象的指针,而只适用于引用。将代码更改为
Foo* foo = new Foo(*this);
无法为指针类型定义隐式转换运算符,因为转换运算符必须是非静态成员函数,因此仅适用于引用。您已正确定义隐式转换运算符,但它不适用于指向对象的指针,而仅适用于引用。将代码更改为
Foo* foo = new Foo(*this);
无法为指针类型定义隐式转换运算符,因为转换运算符必须是非静态成员函数,因此只能应用于引用。@Piotr Skotnicki为什么要删除C++14标记?问题是针对C++14,这是我使用的编译器目前支持的最新标准。因为这里的问题与C++14的功能无关。@Songyuanyo在本例中,我想知道为什么C++14标准修订版会出现这种情况,这是我开发的标准版本)。它可能略有不同,在C++ 03或其他一些C++标准修订。显式总是好的。@Piotr Skotnicki为什么要删除C++14标记?问题是针对C++14,这是我使用的编译器目前支持的最新标准。因为这里的问题与C++14的功能无关。@Songyuanyo在本例中,我想知道为什么C++14标准修订版会出现这种情况,这是我开发的标准版本)。它可能略有不同,在C++ 03或其他一些C++标准修订。直言不讳总是好的。