gpt4 book ai didi

c++ - 使用用户定义的转换运算符隐式转换它

转载 作者:行者123 更新时间:2023-11-27 22:45:30 25 4
gpt4 key购买 nike

假设我有以下代码:

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);

不能为指针类型定义隐式转换运算符,因为转换运算符必须是非静态成员函数,因此只能应用于引用。

关于c++ - 使用用户定义的转换运算符隐式转换它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43535689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com