Классы, которые используют другой класс в качестве возвращаемого типа?

0

Я читал свою книгу на C++, и до сих пор я делаю очень хорошо, но в последнем разделе, который я прочитал, просто идет по моей голове.

Я понимаю типы возврата, но как метод использует другой класс как возвращаемый тип? Когда вы это делаете, вы создаете экземпляр переменных данных и методов из класса Point? Я полностью потерял строку: (а не определение константы или функции, как указано выше)

Point GetUpperLeft() const { return itsUpperLeft; }

Однако эта линия имеет смысл

Point itsUpperLeft;

Потому что класс создает экземпляр класса точки со всеми координатами x и y. Как это делается при работе с функциями, это GetUpperLeft() объект, который также имеет координаты x и y?

Вот остальная часть кода.

// Begin Rectangle.h
2: #include <iostream>
3: class Point // holds x,y coordinates
4: {
5: // no constructor, use default
6: public:
7: void SetX(int x) { itsX = x; }
8: void SetY(int y) { itsY = y; }
9: int GetX()const { return itsX;}
10: int GetY()const { return itsY;}
11: private:
12: int itsX;
13: int itsY;
14: }; // end of Point class declaration
15:
16:
17: class Rectangle
18: {
19: public:
20: Rectangle (int top, int left, int bottom, int right);
21: ~Rectangle () {}
22:
23: int GetTop() const { return itsTop; }
24: int GetLeft() const { return itsLeft; }
25: int GetBottom() const { return itsBottom; }
26: int GetRight() const { return itsRight; }
27:
28: Point GetUpperLeft() const { return itsUpperLeft; }
29: Point GetLowerLeft() const { return itsLowerLeft; }
30: Point GetUpperRight() const { return itsUpperRight; }
31: Point GetLowerRight() const { return itsLowerRight; }
32:
33: void SetUpperLeft(Point Location) {itsUpperLeft = Location;}
34: void SetLowerLeft(Point Location) {itsLowerLeft = Location;}
35: void SetUpperRight(Point Location) {itsUpperRight = Location;}
36: void SetLowerRight(Point Location) {itsLowerRight = Location;}
37:
38: void SetTop(int top) { itsTop = top; }
39: void SetLeft (int left) { itsLeft = left; }
40: void SetBottom (int bottom) { itsBottom = bottom; }
41: void SetRight (int right) { itsRight = right; }
42:
43: int GetArea() const;
44:
45: private:
46: Point itsUpperLeft;
47: Point itsUpperRight;
48: Point itsLowerLeft;
49: Point itsLowerRight;
50: int itsTop;
51: int itsLeft;
52: int itsBottom;
53: int itsRight;
54: };
55: // end Rectangle.h

1: // Begin Rect.cpp
2: #include "Rectangle.h"
3: Rectangle::Rectangle(int top, int left, int bottom, int right)
4: {
5: itsTop = top;
6: itsLeft = left;
7: itsBottom = bottom;
8: itsRight = right;
9:
10: itsUpperLeft.SetX(left);
11: itsUpperLeft.SetY(top);
12:
13: itsUpperRight.SetX(right);
14: itsUpperRight.SetY(top);
15:
16: itsLowerLeft.SetX(left);
17: itsLowerLeft.SetY(bottom);
18:
19: itsLowerRight.SetX(right);
20: itsLowerRight.SetY(bottom);
21: }
22:
23:
24: // compute area of the rectangle by finding sides,
25: // establish width and height and then multiply
26: int Rectangle::GetArea() const
27: {
28: int Width = itsRight-itsLeft;
29: int Height = itsTop - itsBottom;
30: return (Width * Height);
31: }
32:
33: int main()
34: {
35: //initialize a local Rectangle variable
36: Rectangle MyRectangle (100, 20, 50, 80 );
37:
38: int Area = MyRectangle.GetArea();
39:
40: std::cout << "Area: " << Area << "\n";
41: std::cout << "Upper Left X Coordinate: ";
42: std::cout << MyRectangle.GetUpperLeft().GetX();
43: return 0;
44: }
  • 0
    Вы пришли с Java?
  • 0
    Кроме того, Rectangle, вероятно, не должен хранить точку для каждого угла, его избыточность и может привести к неприятностям. Кроме того, участники не должны быть "itsXXX", они должны быть "myXXX".
Показать ещё 1 комментарий
Теги:
class
methods

2 ответа

0
Лучший ответ

Когда GetUpperLeft(), создается копия itsUpperLeft и передается вызывающему устройству GetUpperLeft().

Вы не определили конструктор копирования для class Point (еще не получили копии конструкторов?), Поэтому C++ определит его для вас. Конструктор копии по умолчанию будет просто создавать новый экземпляр class Point и помещать в него копии всех элементов данных его itsUpperLeft (в данном случае только x и y).

Изменить: В частности, если вызывающий код запускает код, например:

Point my_copy = some_rectangle.GetUpperLeft();
my_copy.SetX(13);
my_copy.SetY(12);

не будет никакого эффекта на значения в some_rectangle.itsUpperLeft.

2

itsUpperLeft - это экземпляр класса Point.

GetUpperLeft() в своей текущей форме создает копию своего itsUpperLeft и возвращает эту копию вызывающему.

Затем вызывающий может вызывать методы, такие как GetX(), на этой копии.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню