how can father make friend with son's friend

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
class Box{
    friend ostream& operator<<(ostream& output, const Box& b);
    friend Container& operator+=(Container& c, const Box& b);
    public:
        Box(){};
        Box(std::string n);
        ~Box(){};

    protected:
        int length;
        int width;
        int height;
        double volume;
        std::string name;
    };
class Container:public Box{
    friend ostream& operator<<(ostream& output, const Container& c);
    friend Container& operator+=(Container& c, const Box& b);
    public:
        Container();
        Container(std::string n);
        ~Container(){};

    private:
        int box_num;
};

ostream& operator<<(ostream& output, const Container& c) {
    output<<c.name<<" container "<<c.length<<"x"<<c.width<<endl;
    return output;  // for multiple << operators.}

Container& operator+=(Container& c, const Box& b){
    return c;    };

//in main
1
2
3
4
5
6
7
8
9
10
int main{
Box box1("TV box")
box1.setdimension(4,2,3);
cout << box1;

Container container_TV("Container of TV");
container_TV.setdimension(10,4,3);
cout << container_TV;
container_TV += box1;
}

erro message:
|error: ISO C++ forbids declaration of `Container'


How can I make it work?
You can forward declare Container:
1
2
3
4
5
6
7
8
9
10
11
12
class Container;

class Box
{
    //...
};

class Container
{
    //...
};
=)
Thanks!
Why don't you just move the friend function to Container?

It seems more consistent that it be there than in Box.
you mean as a meber function of Container?
I will have this problem:
error: member `void Container::operator+=(const Box&)' declared as friend before type `Container' defined|
Delete line 3 in your code above.

It can be a friend function, it just needs to be declared in Container, not in Box, since Container is derived from Box (which also seems weird; a Box IS a Container, but not all Containers are Boxes.)



but then I can read the Protected date of Box.

I delete line 3.
And get the erro message :
\Main300.cpp|17|error: `int Box::length' is protected|
Then implement operator<< as a member function.

Or, better yet, implement operator<< on Box as well, and have Container call down to Box::operator<< to output the data members of Box.

Topic archived. No new replies allowed.