Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/163.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 常量和非常量版本和继承_C++_Inheritance_Constants_C++14 - Fatal编程技术网

C++ 常量和非常量版本和继承

C++ 常量和非常量版本和继承,c++,inheritance,constants,c++14,C++,Inheritance,Constants,C++14,在我的问题中,我将有几个类共享getter和setter(在我的例子中是操作符())。假设我有以下几点 class Base { public: int& operator()() { return value; } int operator()() const { return value; } protected: int value; }; class Derived : public Base { publ

在我的问题中,我将有几个类共享getter和setter(在我的例子中是
操作符()
)。假设我有以下几点

class Base
{
    public:
        int& operator()() { return value; }
        int operator()() const { return value; }
    protected:
        int value;
};

class Derived : public Base
{
    public:
        int operator()() const { return value; }
};
我希望能够做这样的事情:

Derived d;
d() = 1;
但是编译器抱怨说表达式是不可赋值的。但是,

Derived d;
d.Base::operator()() = 1;
工作正常。为什么呢?编译器不应该在基类中查找成员函数吗?在派生类中是否有避免重写非常量方法的解决方案

编译器不应该在基类中查找成员函数吗

是的,这是可能的,但你必须明确。为此,您可以使用
using
声明,该声明将运算符引入派生类:

class Derived : public Base
{
    public:
        using Base::operator();
        int operator()() const { return value; }
};

是的,我想是这样的,但是这个
使用
隐藏了我的派生常量版本,它不再被称为()@DragonRock它仍然调用
常量
版本,因为派生类函数总是隐藏具有相同签名的基类函数。唯一的问题是您从未调用
const
函数,因为您的实例不是
const
。我知道,您是对的。如果我
const\u cast
it。谢谢为便于将来参考,这称为“名称隐藏”