1

我有以下课程,

class Base {
public:
    virtual void operator()(string a) {}
    virtual void operator()(int a) {}
};

class Child: public Base {
private:
    std::vector<double> child_vec;
public:
    void operator()(string a) override {
        cout << a << endl;
    }

};

int main() {
    Child child;
    child(9);
}

上面的代码片段给出了编译时错误,模棱两可的重载。但如果我把virtual void operator()(int a) {}它作为一个正常的功能,它就可以工作,

class Base {
public:
    virtual void operator()(string a) {}
    virtual void test(int a) {}
};

class Child: public Base {
private:
    std::vector<double> child_vec;
public:
    void operator()(string a) override {
        cout << a << endl;
    }

};

int main() {
    Child child;
    child.test(9);
}

这是否意味着在基类中有多个虚拟运算符的情况下,我需要覆盖所有这些?

4

1 回答 1

4

问题是operator()Childhides中operator()定义的定义Base

您可以将它们引入Childvia using

class Child: public Base {
private:
    std::vector<double> child_vec;
public:
    using Base::operator();
    void operator()(string a) override {
        cout << a << endl;
    }
};

在您的第二个代码片段中,您将名称更改为test然后没有这样的名称隐藏麻烦。

于 2021-07-16T08:45:02.303 回答