关于c ++:基类中的函数隐藏在子类中。

A function from a base class is being hidden in the subclass. How do I fix this?

在基类中,我有一个函数GetDetections,它接受一个字符串文件名,构造一个功能集,并将其工作延迟到纯虚拟函数GetDetections

在子类中,我实现了这个虚拟函数。

main中,我有一个子类的实例,并用文件名调用GetDetections。我以为这会调用接受字符串参数的基类的非虚函数,但这不会编译。错误是:

prog.cpp: In function ‘int main()’:

prog.cpp:33:48: error: no matching function for call to ‘SubClass::GetDetections(const char [13])’

prog.cpp:33:48: note: candidate is:

prog.cpp:26:9: note: virtual int SubClass::GetDetections(const std::vector&) const
prog.cpp:26:9: note: no known conversion for argument 1 from ‘const char [13]’ to ‘const std::vector&’

这是密码。(也发布在http://ideone.com/85afyx)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <string>
#include <vector>

struct Feature {
  float x;
  float y;
  float value;
};

class BaseClass {
  public:
    int GetDetections(const std::string& filename) const {
        // Normally, I'd read in features from a file, but for this online
        // example, I'll just construct an feature set manually.
        std::vector<Feature> features;
        return GetDetections(features);
    };
    // Pure virtual function.
    virtual int GetDetections(const std::vector<Feature>& features) const = 0;
};

class SubClass : public BaseClass {
  public:
    // Giving the pure virtual function an implementation in this class.
    int GetDetections(const std::vector<Feature>& features) const {
        return 7;
    }
};

int main() {
    SubClass s;
    std::cout << s.GetDetections("testfile.txt");
}

我试过了:

  • 在子类中声明GetDetectionsint GetDetectionsvirtual int GetDetections


在派生类内部使用hide基类中重载的GetDirections函数实现虚函数。

试试这个:

1
2
3
4
using BaseClass::GetDetections;
int GetDetections(const std::vector<Feature>& features) const {
    return 7;
}

子类


重载的虚拟函数被隐藏。但是,您可以使用其限定名称来调用BaseClasseGetDetections

1
std::cout << s.BaseClass::GetDetections("testfile.txt");