+ 1
About references and pointers on classes...
Why the output of the following first code is 3, while the second is 1? #include<iostream> using namespace std; class A{ public: virtual void f() {cout<<1;} }; class B:public A{ public: void f(){cout<<2;} }; class C:public B{ public: void f(){cout<<3;} }; int main() { B *p=new C; p->f(); } ################ #include <iostream> using namespace std; class A{ public: void f(){cout<<1;} }; class B: public A{ private: void f(){cout<<2;} }; void g(A& a){a.f();} int main() { B b; g(b); return 0; }
9 Antworten
+ 2
It has nothing to do with pointer and reference, it is because of the virtual keyword that you have 3 in first input (you should look once again at the course if you do not get it) and because B overloaded function is private that you have 1 instead of 2 in the second case
+ 1
But it seems "private or not" cannot explain the second circumstance, as I've executed the following codes, of which the output was still one. I think it has something to do with some concepts of "reference".
#include <iostream>
using namespace std;
class A{
public:
void f(){cout<<1;}
};
class B: public A{
public:
//private:
void f(){cout<<2;}
};
void g(A& a){a.f();}
int main()
{
B b;
g(b);
return 0;
}
+ 1
Yes as a is of type A and f is not virtual
with the private you removed, directly doing
b.f(); instead of g(b); would have had the same result
+ 1
Very clear and detailed explanation, thanks so much.:)
0
But my interpreter seems not to explain in that way. When directly doing b.f(), I got an error saying "'void B::f()' is private within this context...", rather than using the f() function in base class...
0
Then it is my mistake ! You just can't :)