我对转换运算符的继承感到困惑

I'm confused about inheritance of conversion operator

考虑以下程序:(查看现场演示 here.

#include <iostream>
class Base
{
    int s{9};
    public:
        operator int()
        {
            return s;
        }
};
class Derived : public Base
{
    int s{18};
};
int main()
{
    Base b;
    int s=b;
    std::cout<<s<<'\n';

    Derived d;
    int m=d;
    std::cout<<m;
}

程序输出为:

9

9

这里继承了Baseclass的转换运算符,所以m变量的初始化是有效的

但现在我想打印属于 Derived 的 s 数据成员的值。我该怎么做?

派生的class是否也需要重写转换运算符?我不能重复使用相同的 Base class 转换运算符吗?

Bases 参数在 Derived 中被隐藏,但是由于 Base class 中的转换运算符 Base::s 是在里面使用。 你可以这样做:

class Base
{
    int s{9};
    public:
        Base() {}
        Base(int v) : s(v) {}
        operator int()
        {
            return s;
        }
};
class Derived : public Base
{
public:
    Derived() : Base(18)
    {
    }
};

或者在Derived中写自己的转换运算符。