简体   繁体   中英

How to create different class objects in class constructor and overloading operators (C++)

I need yours help. I'm quite newbie in C++ (still learning) and I struggling with class constructor which include object from different class. The task is to create Rectangle class which will be described by objects (Point class) , each corner is a object with x,y coordinates. Additionally I need overload operators << and >> in the way that by ">>" user input coordinates of each point during Rectangle object creation by constructor. When I using code as below I have error incomplete type is not allowed" on fields from p1 to p4.

List item

    #include <iostream>

using namespace std;

class Point;
class Rectangle
{
public:
    Rectangle(int p1x = 0, int p1y = 0, int p2x = 0, int p2y = 0, int p3x = 0, int p3y = 0, int p4x = 0, int p4y = 0) : p1(p1x, p1y), p2(p2x, p2y), p3(p3x, p3y), p4(p4x, p4y) 
    {

    };

    friend ostream & operator << (ostream &os, const Rectangle &rect);

private:
    Point p1, p2, p3, p4;
    void change_cordinates(Rectangle &);
    int height, width;
};"

From the other hand, when i use #include "Point.h" directive I have problem with overloading << and >> with error "function Rectangle is not a type name"

I don't know if it's clear, but I hope I described my problem peaty clear (if not correct me please or ask)

As already mentioned in the comments: you'll have to ensure types are 'complete' when they are used.

In your example they are used by adding them as member variables. You could work around this issue by holding pointers to them (instead of members) - but that is most likely a bad idea, as you then have to care about memory allocation/de-allocation.

Probably the best solution: include "Point.h" and fix your >> and << operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM