This question already has an answer here:
I faced with compilation error for the following program:
#include <iostream>
class A
{
public:
virtual void f(int i) {
std::cout << "A::f" << std::endl;
}
};
class B : public A
{
public:
virtual void f(int i, int j) {
std::cout << "B::f" << std::endl;
}
};
class C : public B
{
public:
virtual void f(int i) override {
std::cout << "C::f1" << std::endl;
}
virtual void f(int i, int j) override {
std::cout << "C::f2" << std::endl;
}
};
int main(int argc, char* argv[])
{
B * p = new C();
p->f(1);
return 0;
}
When compiling this with gcc version 4.8.5 20150623 (Red Hat 4.8.5-16) as:
g++ test.cpp -std=c++11
the error is:
test.cpp: In function 'int main(int, char**)':
test.cpp:37:11: error: no matching function for call to 'B::f(int)'
p->f(1);
^
test.cpp:37:11: note: candidate is:
test.cpp:15:18: note: virtual void B::f(int, int)
virtual void f(int i, int j) {
^
test.cpp:15:18: note: candidate expects 2 arguments, 1 provided
There will be no error if in main function pointer p
has type C*
, but why class B
does not have void f(int i)
? I expect it should be inherited from A and be available for B just because I can override void f(int i)
in class C
derived from class B
.
Aucun commentaire:
Enregistrer un commentaire