A function from a base class is being hidden in the subclass. How do I fix this?
在基类中,我有一个函数
在子类中,我实现了这个虚拟函数。
在
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"); } |
我试过了:
- 在子类中声明
GetDetections 为int GetDetections ,virtual int GetDetections 。
在派生类内部使用hide基类中重载的
试试这个:
1 2 3 4 | using BaseClass::GetDetections; int GetDetections(const std::vector<Feature>& features) const { return 7; } |
子类
重载的虚拟函数被隐藏。但是,您可以使用其限定名称来调用
1 | std::cout << s.BaseClass::GetDetections("testfile.txt"); |