使用用户定义的转换运算符隐式转换它
Converting this implicitly using an user-defined conversion operator
假设我有以下代码:
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*
的用户定义转换运算符。为什么 this
没有使用上述转换运算符将 隐式 转换为 Base*
?
您已经正确定义了隐式转换运算符,但它不适用于指向您的对象的指针,仅适用于引用。将您的代码更改为
Foo* foo = new Foo(*this);
无法为指针类型定义隐式转换运算符,因为转换运算符必须是非静态成员函数,因此只能应用于引用。
假设我有以下代码:
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*
的用户定义转换运算符。为什么 this
没有使用上述转换运算符将 隐式 转换为 Base*
?
您已经正确定义了隐式转换运算符,但它不适用于指向您的对象的指针,仅适用于引用。将您的代码更改为
Foo* foo = new Foo(*this);
无法为指针类型定义隐式转换运算符,因为转换运算符必须是非静态成员函数,因此只能应用于引用。