Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
 
Рейтинг 4.87/15: Рейтинг темы: голосов - 15, средняя оценка - 4.87
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
1

Объявление класса Point

05.04.2014, 16:40. Показов 2744. Ответов 38
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Объявил класс Point в заголовочном класса для хранения значений координат x,y а далее класс Rectanagle
и вот в классе Rectanagle каждая точка определяет координаты на плоскости линий и используется для создания объекта Rectanagle но при объявлении в нем переменной тип int - требует точку с запятой:

C++
1
2
3
4
5
6
7
8
9
10
11
12
 class Rectangle
{
public:
    Rectangle (int top, int left, int Bottom, int right);
    ~Rectangle ()
    
 
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
Код
В строке int GetTop()  const { return itsTop; }
Здесь сразу встроены функции а их реализация в файле Ractanagle.cpp

Код на C++

C++
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <iostream>
class Point
{
public:
    void setX( int x) { itsX = x; }
    void setY( int y) { itsY = y; }
    int GetX() const { return itsX; }
    int GetY() const { return itsY; }
private:
    int itsX;
    int itsY;
};
 
class Rectangle
{
public:
    Rectangle (int top, int left, int Bottom, int right);
    ~Rectangle ()
    
 
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
 
    Point GetUpperLeft () const { return itsUpperLeft; }
    Point GetLowerleft () const { return itsLowerLeft; }
    Point GetUpperRight () const { return itsUpperRight; }
    Point GetLowerRight () const { return itsLowerRight; }
 
    void SetUpperLeft(Point Location)
           { itsUpperLeft = Location; }
    void SetLowerleft (Point Location) 
           { itsLowerLeft = Location; }
    void SetUpperRight( Point = Location)
           { itsUpperRight = Location; } 
    void SetLowerRigh(Point Location)
           { itsLowerRight = Location; }
 
    void SetTop (int top)               { itsTop = top; }
    void Setleft (int left)             { itsLeft = left; }
    void SetBottom(int bottom)          { itsbottom = bottom;}
    void SetRight(int right)            { itsRight = right; }
 
    int GetArea const;
 
private:
    Point itsUpperLeft;
    Point itsUpperRight;
    Point itsLowerLeft;
    Point itsLowerRight;
    int itsTop;
    int itsLeft;
    int itsBottom;
    int itsRight;
};
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.04.2014, 16:40
Ответы с готовыми решениями:

Объявление объекта класса fstream в качестве статической компоненты другого класса
Доброго времени суток. Есть задание, в котором говорится &quot;...Перепишите программы из упражнений 4 и...

Создать объявление класса и разработать программу-драйвер, которая продемонстрирует работу класса.
Класс Triangle (треугольник). Класс хранит Декартовы координаты трех углов треугольника....

Объявление объекта одного класса в описании другого класса
Здравствуйте. Почему при объявлении Student s в классе Teacher не возникает ошибки? Ведь такой...

Объявление дружественного класса внутри класса
class A{ friend class B{ B(A &amp;a); } } Подскажите пожалуйста, такое...

38
Модератор
Эксперт С++
13507 / 10757 / 6412
Регистрация: 18.12.2011
Сообщений: 28,712
05.04.2014, 17:09 2
C++
1
2
~Rectangle ()
       { } // код деструктора
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
05.04.2014, 17:58  [ТС] 3
А что не так с деструктором-? Конструктор принимает четыре параметра а деструктор по умолчанию и что за код-?
0
3257 / 2059 / 351
Регистрация: 24.11.2012
Сообщений: 4,909
05.04.2014, 18:13 4
zero-11, после объявления деструктора пропущена точка с запятой либо тело.
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 11:42  [ТС] 5
Я проверил весь код - не вижу ошибок:

C++
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
 #include <iostream>
class Point
{
public:
    void setX( int x) { itsX = x; }
    void setY( int y) { itsY = y; }
    int GetX() const { return itsX; }
    int GetY() const { return itsY; }
private:
    int itsX;
    int itsY;
};
 
class Rectangle
{
public:
    Rectangle (int top, int left, int Bottom, int right);
    ~Rectangle ()
    
 
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
 
    Point GetUpperLeft () const { return itsUpperLeft; }
    Point GetLowerleft () const { return itsLowerLeft; }
    Point GetUpperRight () const { return itsUpperRight; }
    Point GetLowerRight () const { return itsLowerRight; }
 
    void SetUpperLeft(Point Location)
           { itsUpperLeft = Location; }
    void SetLowerleft (Point Location) 
           { itsLowerLeft = Location; }
    void SetUpperRight( Point = Location)
           { itsUpperRight = Location; } 
    void SetLowerRigh(Point Location)
           { itsLowerRight = Location; }
 
    void SetTop (int top)               { itsTop = top; }
    void Setleft (int left)             { itsLeft = left; }
    void SetBottom(int bottom)          { itsbottom = bottom;}
    void SetRight(int right)            { itsRight = right; }
 
    int GetArea const;
 
private:
    Point itsUpperLeft;
    Point itsUpperRight;
    Point itsLowerLeft;
    Point itsLowerRight;
    int itsTop;
    int itsLeft;
    int itsBottom;
    int itsRight;
};
Может я чего то не заметил или класс можно объявить иначе:

C++
1
2
3
4
5
6
7
8
9
10
public:
    Rectangle (int top, int left, int Bottom, int right);
    ~Rectangle ()
    
 
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
заранее спасибо.
0
3257 / 2059 / 351
Регистрация: 24.11.2012
Сообщений: 4,909
07.04.2014, 12:04 6
Как еще показать...

Цитата Сообщение от zero-11 Посмотреть сообщение
C++
1
2
3
public:
* * Rectangle (int top, int left, int Bottom, int right);
* * ~Rectangle () {} // < вот тут нужна либо точка с запятой, либо тело
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 12:06 7
Лучший ответ Сообщение было отмечено zero-11 как решение

Решение

Добавить точку с запятой:
C++
18
    ~Rectangle ();
Убрать равно:
C++
36
    void SetUpperRight( Point = Location)
Добавть круглые скобки:
C++
46
    int GetArea() const;
Исправить опечатку в имени переменной:
C++
43
    void SetBottom(int bottom)          { itsbottom = bottom;}

Весь
C++
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
 #include <iostream>
class Point
{
public:
    void setX( int x) { itsX = x; }
    void setY( int y) { itsY = y; }
    int GetX() const { return itsX; }
    int GetY() const { return itsY; }
private:
    int itsX;
    int itsY;
};
 
class Rectangle
{
public:
    Rectangle( int top, int left, int Bottom, int right );
      /*{
        itsTop    = top;
        itsLeft   = left;
        itsBottom = Bottom;
        itsRight  = right;
      }*/
    ~Rectangle ();
      /*{
        top    = 0;
        left   = 0;
        Bottom = 0;
        right  = 0;
      };*/
 
 
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
 
    Point GetUpperLeft () const { return itsUpperLeft; }
    Point GetLowerleft () const { return itsLowerLeft; }
    Point GetUpperRight () const { return itsUpperRight; }
    Point GetLowerRight () const { return itsLowerRight; }
 
    void SetUpperLeft(Point Location)
           { itsUpperLeft = Location; }
    void SetLowerleft (Point Location)
           { itsLowerLeft = Location; }
    void SetUpperRight( Point Location)
           { itsUpperRight = Location; }
    void SetLowerRigh(Point Location)
           { itsLowerRight = Location; }
 
    void SetTop (int top)               { itsTop = top; }
    void Setleft (int left)             { itsLeft = left; }
    void SetBottom(int bottom)          { itsBottom = bottom;}
    void SetRight(int right)            { itsRight = right; }
 
    int GetArea() const;
 
private:
    Point itsUpperLeft;
    Point itsUpperRight;
    Point itsLowerLeft;
    Point itsLowerRight;
    int itsTop;
    int itsLeft;
    int itsBottom;
    int itsRight;
};
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 14:17  [ТС] 8
Все понятно - разобрался. Спасибо.

Добавлено через 1 час 4 минуты
Только еще одна проблема - подключил файл заголовка, к самому исходному коду Rectangle.cpp но не хочет компилировать.

Rectangle.cpp:

C++
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
34
35
36
37
38
39
40
41
42
43
44
45
// Rectangle.cpp: определяет точку входа для консольного приложения.
//
 
#include "stdafx.h"
#include <iostream>
#include "Rectangle.h"
 
Rectangle::Rectangle(int top, int left, int bottom, int right)
{
    itsTop = top;
    itsLeft = left;
    itsBottom = bottom;
    itsRight = right;
 
    itsUpperLeft.setX(left);
    itsUpperLeft.setY(top);
 
    itsUpperRight.setX(right);
    itsUpperRight.setY(top);
 
    itsLowerLeft.setX(left);
    itsLowerLeft.setY(bottom);
 
    itsLowerRight.setX(right);
    itsLowerRight.setY(bottom);
}
 
int Rectangle::GetArea() const
{
    int Width = itsRight - itsLeft;
    int Height = itsTop - itsBottom;
    return ( Width * Height );
}
 
int main()
{
    Rectangle MyRectangle(100, 20, 50, 80 );
 
    int Area = MyRectangle.GetArea();
 
    std::cout << "Area: " << Area << endl;
    std::cout << "Upper Left X Coordinate: ";
    std::cout << MyRectangle.GetUpperLeft().GetX();
    system("PAUSE");
}
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 14:19 9
Цитата Сообщение от zero-11 Посмотреть сообщение
но не хочет компилировать
Накричите на него Какие-нибудь сообщения об ошибках выдает?
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 14:30  [ТС] 10
Да, выдает:

1>------ Построение начато: проект: Rectangle, Конфигурация: Debug Win32 ------
1> Rectangle.cpp
C++
1
2
3
1>Rectangle.obj : error LNK2019: ссылка на неразрешенный внешний символ "public: __thiscall Rectangle::~Rectangle(void)" (??1Rectangle@@QAE@XZ) в функции _main
1>C:\Users\Игорь\Documents\Visual Studio 2010\Projects\Rectangle\Debug\Rectangle.exe : fatal error LNK1120: 1 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 14:40 11
zero-11, ну а где тела конструктора и деструктора? Раскомментируйте их в коде, который я писал чуть выше (и точки с запятой удалите после каждого).

Добавлено через 666 секунд
Хотя к черту. Вот:
код
C++
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class Rectangle
{
public:
    Rectangle( int top, int left, int Bottom, int right )
      {
        itsTop    = top;
        itsLeft   = left;
        itsBottom = Bottom;
        itsRight  = right;
      }
    ~Rectangle ()
      {
        itsTop    = 0;
        itsLeft   = 0;
        itsBottom = 0;
        itsRight  = 0;
      };
 
 
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
 
    Point GetUpperLeft () const { return itsUpperLeft; }
    Point GetLowerleft () const { return itsLowerLeft; }
    Point GetUpperRight () const { return itsUpperRight; }
    Point GetLowerRight () const { return itsLowerRight; }
 
    void SetUpperLeft(Point Location)
           { itsUpperLeft = Location; }
    void SetLowerleft (Point Location)
           { itsLowerLeft = Location; }
    void SetUpperRight( Point Location)
           { itsUpperRight = Location; }
    void SetLowerRigh(Point Location)
           { itsLowerRight = Location; }
 
    void SetTop (int top)               { itsTop = top; }
    void Setleft (int left)             { itsLeft = left; }
    void SetBottom(int bottom)          { itsBottom = bottom;}
    void SetRight(int right)            { itsRight = right; }
 
    int GetArea() const;
 
private:
    Point itsUpperLeft;
    Point itsUpperRight;
    Point itsLowerLeft;
    Point itsLowerRight;
    int itsTop;
    int itsLeft;
    int itsBottom;
    int itsRight;
};
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 14:43  [ТС] 12
Но функция GetX - функция доступа к переменной x - int GetX - определена и поэтому он не должен ссылаться на невозможность получить доступ к классу Point - функция доступа int GetX() имеет встроенное определение int GetX() const { return itsX } и является функцией доступа класса Point.

Или же дело в деструкторе:

Код
1>Rectangle.obj : error LNK2019: ссылка на неразрешенный внешний символ "public: __thiscall Rectangle::~Rectangle(void)" (??1Rectangle@@QAE@XZ) в функции _main
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 14:50 13
Продолжая отвлеченный разговор, можно наблюдать интересный факт, как студия наглядно обзывает функции:
Код
??1Rectangle@@QAE@XZ
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 14:52  [ТС] 14
Все равно:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Rectangle
{
public:
    Rectangle( int top, int left, int Bottom, int right );
      {
        itsTop    = top;
        itsLeft   = left;
        itsBottom = Bottom;
        itsRight  = right;
      }
    ~Rectangle ();
     {
        top    = 0;
        left   = 0;
        Bottom = 0;
        right  = 0;
      };
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
Код на С++

C++
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;
class Point
{
public:
    void setX( int x) { itsX = x; }
    void setY( int y) { itsY = y; }
    int GetX() const { return itsX; }
    int GetY() const { return itsY; }
private:
    int itsX;
    int itsY;
};
 
class Rectangle
{
public:
    Rectangle( int top, int left, int Bottom, int right );
      {
        itsTop    = top;
        itsLeft   = left;
        itsBottom = Bottom;
        itsRight  = right;
      }
    ~Rectangle ();
     {
        top    = 0;
        left   = 0;
        Bottom = 0;
        right  = 0;
      };
    
    int GetTop()  const { return itsTop; }
    int GetLeft() const { return itsLeft; }
    int GetBottom() const { return itsBottom; }
    int GetRight() const { return itsRight; }
 
    Point GetUpperLeft () const { return itsUpperLeft; }
    Point GetLowerleft () const { return itsLowerLeft; }
    Point GetUpperRight () const { return itsUpperRight; }
    Point GetLowerRight () const { return itsLowerRight; }
 
    void SetUpperLeft(Point Location)
           { itsUpperLeft = Location; }
    void SetLowerleft (Point Location) 
           { itsLowerLeft = Location; }
    void SetUpperRight( Point  Location)
           { itsUpperRight = Location; } 
    void SetLowerRigh(Point Location)
           { itsLowerRight = Location; }
 
 
    void SetTop (int top)               { itsTop = top; }
    void Setleft (int left)             { itsLeft = left; }
    void SetBottom(int bottom)          { itsBottom = bottom;}
    void SetRight(int right)            { itsRight = right; }
 
    int GetArea() const;
    
private:
    Point itsUpperLeft;
    Point itsUpperRight;
    Point itsLowerLeft;
    Point itsLowerRight;
    int itsTop;
    int itsLeft;
    int itsBottom;
    int itsRight;
};
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 14:57 15
Цитата Сообщение от zero-11 Посмотреть сообщение
Все равно
Нет. Мне не все равно. Или скопируйте полностью мой код или прислушайтесь к замечанию в скобочках:
в четвертой и в одиннадцатой строке уберите точку с запятой.
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 15:14  [ТС] 16
Убрал:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Rectangle
{
public:
    Rectangle( int top, int left, int Bottom, int right )
      {
        itsTop    = top;
        itsLeft   = left;
        itsBottom = Bottom;
        itsRight  = right;
      }
    ~Rectangle ()
     {
        top    = 0;
        left   = 0;
        Bottom = 0;
        right  = 0;
      };
не определены:

C++
1
2
3
4
5
6
 {
        top    = 0;
        left   = 0;
        Bottom = 0;
        right  = 0;
      };
0
3257 / 2059 / 351
Регистрация: 24.11.2012
Сообщений: 4,909
07.04.2014, 15:18 17
zero-11, в классе и нет таких полей. В вашем случае у полей префикс - its.
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 15:23 18

Не по теме:

Хотел найти картинку с буддой, но не нашел.



zero-11, перепишите деструктор вот так:
C++
1
2
3
4
5
6
7
    ~Rectangle ()
     {
        itsTop    = 0;
        itsLeft   = 0;
        itsBottom = 0;
        itsRight  = 0;
      };
0
0 / 0 / 0
Регистрация: 21.03.2014
Сообщений: 56
07.04.2014, 15:26  [ТС] 19
Уже пробовал - ни в какую!
0
Почетный модератор
Эксперт С++
5850 / 2861 / 392
Регистрация: 01.11.2011
Сообщений: 6,907
07.04.2014, 15:28 20
Цитата Сообщение от zero-11 Посмотреть сообщение
Уже пробовал - ни в какую!
Уже слышали. Приводите ошибки. (и за одно полный код с последними правками)
0
07.04.2014, 15:28
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
07.04.2014, 15:28
Помогаю со студенческими работами здесь

Шаблон класса Point
Создайте шаблонный класс Point (Точка), у которого есть две координаты. Каждая из координат должна...

Предварительное объявление класса
Имеется код такого вида: class IBase { public: virtual foo() = NULL; .. .. .. };

Объявление класса Patient
Доброго времени суток! Есть программа, в ней несколько файлов. Есть класс Patient, на который...

Объявление класса с шаблоном
Пишу в Qt. Создал класс с шаблоном matrix.h #ifndef MATRIX_H #define MATRIX_H template...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
20
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru