classes (concrete & concrete2), but I have a problem because I have to
access to a third class (element) and if I try to declare interface
class as friend, I obtain this (right) error:
[err]
main2.cpp: In member function `virtual void
concrete::method(element&)':
main2.cpp:8: error: `int element::a_int' is protected
main2.cpp:31: error: within this context
main2.cpp: In member function `virtual void
concrete2::method(element&)':
main2.cpp:8: error: `int element::a_int' is protected
main2.cpp:39: error: within this context
[/err]
So the question is, there is a way to realize this?
I don't would use the interface as a wrapper, nor solve the problem
with a design pattern, any ideas?
This is the example code:
Expand|Select|Wrap|Line Numbers
- #include <iostream>
- using namespace std;
- class element
- {
- protected:
- int a_int;
- public:
- element(int a) { a_int = a; };
- ~element();
- // friend class interface; // --> I would declare just this line!
- friend class concrete;
- friend class concrete2;
- };
- class interface
- {
- public:
- interface() {};
- ~interface() {};
- virtual void method(element & e) = 0;
- };
- class concrete : public interface
- {
- public:
- concrete() {};
- ~concrete() {};
- void method(element & e) { cout << "[1] " << e.a_int <<
- endl;};
- };
- class concrete2 : public interface
- {
- public:
- concrete2() {};
- ~concrete2() {};
- void method(element & e) { cout << "[2] " << e.a_int <<
- endl;};
- };
- int main()
- {
- element * e = new element(10);
- interface * i;
- concrete * c = new concrete();
- concrete2 * c2 = new concrete2();
- i = c;
- i->method(*e);
- i = c2;
- i->method(*e);
- return 0;
- }