Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск  
 
 
Рейтинг 4.87/15: Рейтинг темы: голосов - 15, средняя оценка - 4.87
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334

Что не так в перегрузке оператора индексирования?

22.07.2019, 00:13. Показов 3982. Ответов 49
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
C++
1
Star& operator[](const int index);
C++
1
2
3
4
Star& Galaxy::operator[](const int index)
{
    return stars[index];
}
C++
1
2
3
4
Sputnik sp(name, 12, 3);
    Star star(12,3,1,name,4,sp);
    Galaxy gal(3);
    gal[0] = star;
Подскажите в чем ошибка ?
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
22.07.2019, 00:13
Ответы с готовыми решениями:

Перегрузка оператора индексирования
Всем привет! Ситуация такая - есть 2 класса, поле одного класса является массивом из элементов второго класса. Необходимо переопределить...

Перегрузка оператора индексирования
Собсно код с книжки списал. Понятно что данный класс на векторе построен (понятно, что можно на основе любого контейнера зафигачить),...

Перегрузка оператора индексирования
Что-то не выходит каменный цветок. Определение класса: struct TEventData { char strComputerName; }; class TEventDataSet { ...

49
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 01:30  [ТС]
Студворк — интернет-сервис помощи студентам
IGPIGP, Я их выложу,для того что бы вы подсказали в чем проблема
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
#pragma once
#include"Sputnik.h"
#include<iostream>
#include<istream>
#include<ostream>
class Planet
{
private:
    char* name;
    int Way;
    Sputnik sputnik;
public:
    friend std::ostream& operator <<(std::ostream& out, const Planet& value);
    friend std::istream& operator >>(std::istream& in, Planet& value);
    
 
    Planet();
    Planet(char *name, int way, Sputnik value);
 
    void SetName(char* value);
    char* GetName()const;
    void SetWay(int value);
    int GetWay() const;
    void SetSpt(Sputnik sp);
    Sputnik GetSpt() const;
    Planet(const Planet &paramtr);
    void Info();
    virtual void One_of_fields();
    ~Planet();
};

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
70
71
72
73
74
75
76
77
78
#include "Planet.h"
#include<iostream>
#include<istream>
#include<ostream>
using namespace std;
void Planet::SetName(char* value)
{
    name = new char[strlen(value) + 1];
    strcpy_s(name, strlen(value) + 1, value);
}
char* Planet::GetName()const
{
    return name;
}
void Planet::SetWay(int value)
{
    Way = value;
}
int Planet::GetWay() const
{
    return Way;
}
void Planet::SetSpt(Sputnik value)
{
    sputnik = value;
}
Sputnik Planet::GetSpt()const
{
    return sputnik;
}
Planet::Planet()
{
    Way = 0;
    name = new char[80];
    name[79] = '\0';
}
Planet::Planet(char* Name, int way, Sputnik sp)
{
    name = new char[strlen(Name) + 1];
    strcpy_s(name, strlen(Name) + 1, Name);
    Way = way;
 
    sputnik.SetMass(sp.GetMass());
    sputnik.SetName(sp.GetName());
    sputnik.SetRadius(sp.GetRadius());
}
Planet::Planet(const Planet &value)
{
    name = new char[10];
    strcpy_s(name, 10, value.name);
    Way = value.Way;
    sputnik = value.sputnik;
}
 
std::ostream& operator << (std::ostream& out, const Planet& value)
{
 
    return(out << "Имя: " << value.GetName() << " ; Путь: " << value.GetWay());// << " ; Радиус спутника: " << value.GetSpt().GetRadius() << " ; Масса спутника: " << value.GetSpt().GetMass() << " ; Имя спутника: " << value.GetSpt().GetName());
}
 
std::istream& operator >> (std::istream& in, Planet& value)
{
 
    return in >> value.name >> value.Way;
}
void Planet::Info() {}
//{
//  cout << "Name:" << " " << name << " Way:" << " " << Way << " Sputnik:" << " " << " His Name:" << sputnik.GetName() << " " << " His Mass:" << sputnik.GetMass() << " " << " His Radius:" << sputnik.GetRadius();
//}
void Planet::One_of_fields() { cout << "virtual function" << endl; }
//{
//  cout << "Расстояние " << Way;
//}
 
Planet::~Planet()
{
    delete[]name;
}
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
#pragma once
#include"Planet.h"
class Star : public Planet
{
private:
    int time;
    int temperature;
    int diapasone;
 
public:
 
    Star();
    bool operator == (const Star& value);
    Star(bool value);
    Star(int _time, int _temp, int _diapasone, char * _name, int _way, Sputnik sp);
    void SetTime(int _time);
    int GetTime() const;
    void SetTemp(int _temp);
    int GetTemp()const;
    void SetDiapasone(int _diapasone);
    int GetDiapasone()const;
    void Info();
    void One_of_fields() override;
    Star(const Star &paramtr);
};
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 "Star.h"
#include<iostream>
using namespace std;
Star::Star()
{
    time = 0;
    temperature = 0;
    diapasone = 0;
}
Star::Star(int _time, int _temp, int _diapasone, char * _name, int _way, Sputnik sp) :
    Planet(_name, _way, sp)
{
    diapasone = _diapasone;
    time = _time;
    temperature = _temp;
}
void Star::SetTime(int _time)
{
    time = _time;
}
int Star::GetTime()const
{
    return time;
}
void Star::SetTemp(int _temp)
{
    temperature = _temp;
}
int Star::GetTemp()const
{
    return temperature;
}
void Star::SetDiapasone(int _diapasone)
{
    diapasone = _diapasone;
}
int Star::GetDiapasone()const
{
    return diapasone;
}
void Star::One_of_fields() 
{
    cout << "ovveride fucntion" << endl;
    //cout << "Температура " << temperature << endl;
}
bool Star::operator == (const Star& value)
{
    return GetTime() == value.GetTime() & GetTemp() == value.GetTemp() & GetDiapasone() == value.GetDiapasone();
}
 
Star::Star(bool value) {}
void Star::Info()
{
    cout << "Название планеты,возле которой находится звезда: " << GetName();
    cout << " Расстояние от планеты к звезде: " << GetWay();
    cout << " Масса спутника: " << GetSpt().GetMass();
    cout << " Название спутника: " << GetSpt().GetName();
    cout << " Радиус спутника: " << GetSpt().GetRadius();
    cout << " Диапазон звезды: " << diapasone;
    cout << " Время звезды:" << time;
    cout << " Температура звезды: " << temperature;
}
Star::Star(const Star &value)
{
    time = value.time;
    temperature = value.temperature;
    diapasone = value.diapasone;
}
Вот классы Star и Planet

Добавлено через 1 минуту
Цитата Сообщение от IGPIGP Посмотреть сообщение
завалить этот код можно задав слишком длинное имя
согласен,но я ввожу имя на 3 символа
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 01:44
Макрой, отсутствует operator= для Star, так же кривое управление ресурсами, как и в Galaxy. Вангую те же проблемы и в классе Sputnik.
1
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 02:39  [ТС]
zayats80888,
C++
1
Star operator =(const Star& v);
C++
1
2
3
4
5
6
7
Star Star::operator =(const Star& v)
{
    this->time = v.time;
    this->diapasone = v.diapasone;
    this->temperature = v.temperature;
    return *this;
}
добавил оператор для Star
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 03:32
Цитата Сообщение от Макрой Посмотреть сообщение
добавил оператор для Star
Я имел ввиду Planet, т.к. в этом классе у вас char* name В Star его уберите или внутри него вызывайте Planet::operator=(v). Также принято возвращать ссылку, а не временный объект. То же относится и к Sputnik, если в нем динамическое управление ресурсами.
0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 16:48  [ТС]
zayats80888,
Вот посмотрите пожалуйста
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
//Planet.h
#pragma once
#include"Sputnik.h"
#include<iostream>
#include<istream>
#include<ostream>
class Planet
{
private:
    char* name;
    int Way;
    Sputnik sputnik;
public:
    friend std::ostream& operator <<(std::ostream& out, const Planet& value);
    friend std::istream& operator >>(std::istream& in, Planet& value);
    
 
    Planet();
    Planet(char *name, int way, Sputnik value);
    Planet operator =(const Planet& v);
    void SetName(char* value);
    char* GetName()const;
    void SetWay(int value);
    int GetWay() const;
    void SetSpt(Sputnik sp);
    Sputnik GetSpt() const;
    Planet(const Planet &paramtr);
    void Info();
    virtual void One_of_fields();
    ~Planet();
};
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//Planet.cpp
#include "Planet.h"
#include<iostream>
#include<istream>
#include<ostream>
using namespace std;
void Planet::SetName(char* value)
{
    name = new char[strlen(value) + 1];
    strcpy_s(name, strlen(value) + 1, value);
}
char* Planet::GetName()const
{
    return name;
}
void Planet::SetWay(int value)
{
    Way = value;
}
int Planet::GetWay() const
{
    return Way;
}
void Planet::SetSpt(Sputnik value)
{
    sputnik = value;
}
Sputnik Planet::GetSpt()const
{
    return sputnik;
}
Planet::Planet()
{
    Way = 0;
    name = new char[80];
    name[79] = '\0';
}
Planet::Planet(char* Name, int way, Sputnik sp)
{
    name = new char[strlen(Name) + 1];
    strcpy_s(name, strlen(Name) + 1, Name);
    Way = way;
 
    sputnik.SetMass(sp.GetMass());
    sputnik.SetName(sp.GetName());
    sputnik.SetRadius(sp.GetRadius());
}
Planet::Planet(const Planet &value)
{
    name = new char[10];
    strcpy_s(name, 10, value.name);
    Way = value.Way;
    sputnik = value.sputnik;
}
 
std::ostream& operator << (std::ostream& out, const Planet& value)
{
 
    return(out << "Имя: " << value.GetName() << " ; Путь: " << value.GetWay());// << " ; Радиус спутника: " << value.GetSpt().GetRadius() << " ; Масса спутника: " << value.GetSpt().GetMass() << " ; Имя спутника: " << value.GetSpt().GetName());
}
Planet Planet::operator =(const Planet& v)
{
    this->name = v.name;
    this->sputnik = v.sputnik;
    this->Way = v.Way;
    return *this;
}
std::istream& operator >> (std::istream& in, Planet& value)
{
 
    return in >> value.name >> value.Way;
}
void Planet::Info() {}
//{
//  cout << "Name:" << " " << name << " Way:" << " " << Way << " Sputnik:" << " " << " His Name:" << sputnik.GetName() << " " << " His Mass:" << sputnik.GetMass() << " " << " His Radius:" << sputnik.GetRadius();
//}
void Planet::One_of_fields() { cout << "virtual function" << endl; }
//{
//  cout << "Расстояние " << Way;
//}
 
Planet::~Planet()
{
    delete[]name;
}
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
//Sputnik.h
#pragma once
#include<string.h>
#include<ostream>
class Sputnik
{
private:
    char *name;
    double mass;
    double radius;
 
public:
    friend std::ostream& operator <<(std::ostream& out, const Sputnik& value);
    friend std::istream& operator >>(std::istream& in, Sputnik& value);
    Sputnik operator =(const Sputnik& v);
    Sputnik(double a) :radius(a) {};
    Sputnik(double a, double b, char* name2) :radius(a), mass(b)
    {
        name = new char[strlen(name2) + 1];
        strcpy_s(name, strlen(name2) + 1, name2);
    }
    Sputnik operator+(const Sputnik&);
    Sputnik();
    const Sputnik& operator ++() { ++radius;return *this; }
 
    double Get() { return radius; }
 
    double Get_m()
    {
        return mass;
    }
    Sputnik(char * name2, double mass2, double radius2);
 
    void SetName(char * value);
 
    char* GetName()const;
 
    void SetMass(double value);
 
    double GetMass()const;
 
    void SetRadius(double value);
 
    double GetRadius()const;
 
    void Info();
    void Show_one_of_fields();
    Sputnik(const Sputnik &parametr);
 
    ~Sputnik();
 
};
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//Sputnik.cpp
#include "Sputnik.h"
#include "iostream"
#include<string.h>
#include<ostream>
using namespace std;
void Sputnik::SetName(char * value)
{
    delete[]name;
    name = new char[strlen(value) + 1];
    strcpy_s(name, strlen(value) + 1, value);
 
}
char* Sputnik::GetName()const
{
    return name;
}
void Sputnik::SetMass(double value)
{
    mass = value;
}
double Sputnik::GetMass()const
{
    return mass;
}
void Sputnik::SetRadius(double value)
{
    radius = value;
}
double Sputnik::GetRadius()const
{
    return radius;
}
Sputnik::Sputnik()
{
    name = new char[6];
    //name[79] = '\0';
    strcpy_s(name, 6, "First");
    mass = 0;
    radius = 0;
}
Sputnik::Sputnik(char * name2, double mass2, double radius2)
{
    name = new char[strlen(name2) + 1];
    strcpy_s(name, strlen(name2) + 1, name2);
 
    mass = mass2;
    radius = radius2;
}
Sputnik::Sputnik(const Sputnik &value)
{
    
    mass = value.mass;
    radius = value.radius;
    name = new char[strlen(value.name)+1];
    strcpy_s(name, strlen(value.name)+1, value.name);
}
void Sputnik::Info()
{
    cout << "Name:" << " " << name << " " << " Radius:" << " " << radius << " Mass:" << " " << mass << endl;
}
void Sputnik::Show_one_of_fields()
{
    cout << name;
}
Sputnik Sputnik :: operator+(const Sputnik& a)
{
    return Sputnik(GetRadius(), mass + a.mass, GetName());
}
std::istream& operator >> (std::istream& in, Sputnik& value)
{
 
    return in >> value.name >> value.mass >> value.radius;
}
std::ostream& operator <<(std::ostream& out, const Sputnik& value)
{
 
    return(out << "Имя: " << value.GetName() << " ; Масса: " << value.GetMass() << " ; Радиус: " << value.GetRadius());
}
Sputnik Sputnik::operator =(const Sputnik& v)
{
    this->mass = v.mass;
    this->name = v.name;
    this->radius = v.radius;
    return *this;
}
Sputnik ::~Sputnik()
{
    delete[]name;
 
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//Galaxy.h
#pragma once
#include"Star.h"
#include<assert.h>
class Galaxy
{
private:
    int date;
    int length;
    Star* stars;
public:
    int Get_Date();
    void Set_Date(int value);
    int Get_Length();
    void Set_Length(int value);
    Star& operator[](const int index);
    Galaxy operator =(const Galaxy& v);
    Galaxy();
    
    Galaxy( int _length);
    Galaxy(int _data, Star* _satrs);
    ~Galaxy();
};
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
//Galaxy.cpp
#include "Galaxy.h"
#include"Star.h"
#include<iostream>
#include<assert.h>
using namespace std;
Galaxy::Galaxy()
{
 
    stars = new Star[0];
    length = 0;
    date = 0;
}
void Galaxy::Set_Date(int value)
{
    date = value;
}
int Galaxy::Get_Date()
{
    return date;
}
void Galaxy::Set_Length(int value)
{
    length = value;
}
int Galaxy::Get_Length()
{
    return length;
}
Star& Galaxy::operator[](const int index)
{
    return stars[index];
}
 
Galaxy::Galaxy( int _length)
{
  stars = new Star[_length];
    
}
Galaxy Galaxy::operator =(const Galaxy& v)
{
    stars = new Star[v.length];
    for (int i = 0;i < v.length;i++)
    {
        this->stars[i] = v.stars;
    }
    return *this;
}
 
Galaxy::Galaxy(int _data, Star*_stars )
{
    date = _data;
    stars->SetDiapasone(_stars->GetDiapasone());
    stars->SetName(_stars->GetName());
    stars->SetSpt(_stars->GetSpt());
    stars->SetTemp(_stars->GetTemp());
    stars->SetTime(_stars->GetTime());
    stars->SetWay(_stars->GetWay());
}
Galaxy::~Galaxy()
{
    delete[]stars;
}
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//main
#include"Planet.h"
#include"Star.h"
#include"Galaxy.h"
#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    char* name = new char[10];
    cin >> name;
    Sputnik sp(name, 12, 3);
    Star star(12,3,1,name,4,sp);
    Galaxy gal(1);
    gal[0] = star;
    cout << gal[0] << endl;
    cin.get();
    cin.get();
    return 0;
}
В классе Star я убрал перегруженный оператор =
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 17:20
Макрой,
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//...
Sputnik::Sputnik(const Sputnik &value) :Sputnik(value.name, value.mass, value.radius) {}
//...
Sputnik& Sputnik::operator =(const Sputnik& v)
{
    delete[] name;
    size_t str_sz = strlen(v.name) + 1;
    name = new char[str_sz];
    strcpy_s(name, str_sz, v.name);
 
    mass = v.mass;
    radius = v.radius;
    return *this;
}
//...
Аналогично для остальных классов где есть поля указатели

Добавлено через 3 минуты

Не по теме:

Вам кто-то запрещает пользоваться std::string и std::vector?

2
23.07.2019, 17:27

Не по теме:

Цитата Сообщение от Макрой Посмотреть сообщение
IGPIGP, Я их выложу,для того что бы вы подсказали в чем проблема
Как-то медленно оно у вас. Постепенно) Но однако смотрите, уже пришла и подмога. Слушайте zayats80888, - он плохого не скажет).

0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 17:38
Макрой, забыл еще проверку на самоприсваивание, первой строчкой в операторе = добавьте if (this == &v) return *this;

Не по теме:

Цитата Сообщение от IGPIGP Посмотреть сообщение
он плохого не скажет)
Да, я не ругаюсь, но от того, что бы не сморозить глупость, никто не застрахован :)

0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 18:05  [ТС]
zayats80888,
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
//Star.h
#pragma once
#include"Planet.h"
class Star : public Planet
{
private:
    int time;
    int temperature;
    int diapasone;
 
public:
    friend std::ostream& operator <<(std::ostream& out, const Star& value);
    Star();
    bool operator == (const Star& value);
    Star(bool value);
    Star(int _time, int _temp, int _diapasone, char * _name, int _way, Sputnik sp);
    void SetTime(int _time);
    int GetTime() const;
    void SetTemp(int _temp);
    int GetTemp()const;
    void SetDiapasone(int _diapasone);
    int GetDiapasone()const;
    void Info();
    void One_of_fields() override;
    Star(const Star &paramtr);
    
};
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
70
71
72
73
74
//Star.cpp
#include "Star.h"
#include<iostream>
using namespace std;
Star::Star()
{
    time = 0;
    temperature = 0;
    diapasone = 0;
}
Star::Star(int _time, int _temp, int _diapasone, char * _name, int _way, Sputnik sp) :
    Planet(_name, _way, sp)
{
    diapasone = _diapasone;
    time = _time;
    temperature = _temp;
}
void Star::SetTime(int _time)
{
    time = _time;
}
int Star::GetTime()const
{
    return time;
}
void Star::SetTemp(int _temp)
{
    temperature = _temp;
}
int Star::GetTemp()const
{
    return temperature;
}
void Star::SetDiapasone(int _diapasone)
{
    diapasone = _diapasone;
}
int Star::GetDiapasone()const
{
    return diapasone;
}
void Star::One_of_fields() 
{
    cout << "ovveride fucntion" << endl;
    //cout << "Температура " << temperature << endl;
}
bool Star::operator == (const Star& value)
{
    return GetTime() == value.GetTime() & GetTemp() == value.GetTemp() & GetDiapasone() == value.GetDiapasone();
}
std::ostream& operator << (std::ostream& out, const Star& value)
{
 
    return(out <<"Диапазон звезды: "<<value.GetDiapasone()<<" Время звезды: "<< value.GetTime()<<" Температура звезды: "<<value.GetTemp());
}
Star::Star(bool value) {}
void Star::Info()
{
    cout << "Название планеты,возле которой находится звезда: " << GetName();
    cout << " Расстояние от планеты к звезде: " << GetWay();
    cout << " Масса спутника: " << GetSpt().GetMass();
    cout << " Название спутника: " << GetSpt().GetName();
    cout << " Радиус спутника: " << GetSpt().GetRadius();
    cout << " Диапазон звезды: " << diapasone;
    cout << " Время звезды:" << time;
    cout << " Температура звезды: " << temperature;
}
 
Star::Star(const Star &value)
{
    time = value.time;
    temperature = value.temperature;
    diapasone = value.diapasone;
}
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
//Planet.h
#pragma once
#include"Sputnik.h"
#include<iostream>
#include<istream>
#include<ostream>
class Planet
{
private:
    char* name;
    int Way;
    Sputnik sputnik;
public:
    friend std::ostream& operator <<(std::ostream& out, const Planet& value);
    friend std::istream& operator >>(std::istream& in, Planet& value);
    
 
    Planet();
    Planet(char *name, int way, Sputnik value);
    Planet operator =(const Planet& v);
    void SetName(char* value);
    char* GetName()const;
    void SetWay(int value);
    int GetWay() const;
    void SetSpt(Sputnik sp);
    Sputnik GetSpt() const;
    Planet(const Planet &paramtr);
    void Info();
    virtual void One_of_fields();
    ~Planet();
};
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//Planet.cpp
#include "Planet.h"
#include<iostream>
#include<istream>
#include<ostream>
using namespace std;
void Planet::SetName(char* value)
{
    name = new char[strlen(value) + 1];
    strcpy_s(name, strlen(value) + 1, value);
}
char* Planet::GetName()const
{
    return name;
}
void Planet::SetWay(int value)
{
    Way = value;
}
int Planet::GetWay() const
{
    return Way;
}
void Planet::SetSpt(Sputnik value)
{
    sputnik = value;
}
Sputnik Planet::GetSpt()const
{
    return sputnik;
}
Planet::Planet()
{
    Way = 0;
    name = new char[80];
    name[79] = '\0';
}
Planet::Planet(char* Name, int way, Sputnik sp)
{
    name = new char[strlen(Name) + 1];
    strcpy_s(name, strlen(Name) + 1, Name);
    Way = way;
 
    sputnik.SetMass(sp.GetMass());
    sputnik.SetName(sp.GetName());
    sputnik.SetRadius(sp.GetRadius());
}
Planet::Planet(const Planet &value)
{
    name = new char[10];
    strcpy_s(name, 10, value.name);
    Way = value.Way;
    sputnik = value.sputnik;
}
 
std::ostream& operator << (std::ostream& out, const Planet& value) 
{
    
    return(out << "Имя: " << value.GetName() << " ; Путь: " << value.GetWay());// << " ; Радиус спутника: " << value.GetSpt().GetRadius() << " ; Масса спутника: " << value.GetSpt().GetMass() << " ; Имя спутника: " << value.GetSpt().GetName());
}
Planet Planet::operator =(const Planet& v)
{
    if (this == &v) return *this;
    delete[] name;
    
    name = new char[strlen(v.name) + 1];
    strcpy_s(name, strlen(v.name) + 1, v.name);
    this->Way = v.Way;
    this->sputnik = v.sputnik;
    return *this;
}
std::istream& operator >> (std::istream& in, Planet& value)
{
 
    return in >> value.name >> value.Way;
}
void Planet::Info() {}
//{
//  cout << "Name:" << " " << name << " Way:" << " " << Way << " Sputnik:" << " " << " His Name:" << sputnik.GetName() << " " << " His Mass:" << sputnik.GetMass() << " " << " His Radius:" << sputnik.GetRadius();
//}
void Planet::One_of_fields() { cout << "virtual function" << endl; }
//{
//  cout << "Расстояние " << Way;
//}
 
Planet::~Planet()
{
    delete[]name;
}
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
//Sputnik.h
#pragma once
#include<string.h>
#include<ostream>
class Sputnik
{
private:
    char *name;
    double mass;
    double radius;
 
public:
    friend std::ostream& operator <<(std::ostream& out, const Sputnik& value);
    friend std::istream& operator >>(std::istream& in, Sputnik& value);
    Sputnik operator =(const Sputnik& v);
    Sputnik(double a) :radius(a) {};
    Sputnik(double a, double b, char* name2) :radius(a), mass(b)
    {
        name = new char[strlen(name2) + 1];
        strcpy_s(name, strlen(name2) + 1, name2);
    }
    Sputnik operator+(const Sputnik&);
    Sputnik();
    const Sputnik& operator ++() { ++radius;return *this; }
 
    double Get() { return radius; }
 
    double Get_m()
    {
        return mass;
    }
    Sputnik(char * name2, double mass2, double radius2);
 
    void SetName(char * value);
 
    char* GetName()const;
 
    void SetMass(double value);
 
    double GetMass()const;
 
    void SetRadius(double value);
 
    double GetRadius()const;
 
    void Info();
    void Show_one_of_fields();
    Sputnik(const Sputnik &parametr);
 
    ~Sputnik();
 
};
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//Sputnik.cpp
#include "Sputnik.h"
#include "iostream"
#include<string.h>
#include<ostream>
using namespace std;
void Sputnik::SetName(char * value)
{
    delete[]name;
    name = new char[strlen(value) + 1];
    strcpy_s(name, strlen(value) + 1, value);
 
}
char* Sputnik::GetName()const
{
    return name;
}
void Sputnik::SetMass(double value)
{
    mass = value;
}
double Sputnik::GetMass()const
{
    return mass;
}
void Sputnik::SetRadius(double value)
{
    radius = value;
}
double Sputnik::GetRadius()const
{
    return radius;
}
Sputnik::Sputnik()
{
    name = new char[6];
    //name[79] = '\0';
    strcpy_s(name, 6, "First");
    mass = 0;
    radius = 0;
}
Sputnik::Sputnik(char * name2, double mass2, double radius2)
{
    name = new char[strlen(name2) + 1];
    strcpy_s(name, strlen(name2) + 1, name2);
 
    mass = mass2;
    radius = radius2;
}
Sputnik::Sputnik(const Sputnik &value)
{
    
    mass = value.mass;
    radius = value.radius;
    name = new char[strlen(value.name)+1];
    strcpy_s(name, strlen(value.name)+1, value.name);
}
void Sputnik::Info()
{
    cout << "Name:" << " " << name << " " << " Radius:" << " " << radius << " Mass:" << " " << mass << endl;
}
void Sputnik::Show_one_of_fields()
{
    cout << name;
}
Sputnik Sputnik :: operator+(const Sputnik& a)
{
    return Sputnik(GetRadius(), mass + a.mass, GetName());
}
std::istream& operator >> (std::istream& in, Sputnik& value)
{
 
    return in >> value.name >> value.mass >> value.radius;
}
std::ostream& operator <<(std::ostream& out, const Sputnik& value)
{
 
    return(out << "Имя: " << value.GetName() << " ; Масса: " << value.GetMass() << " ; Радиус: " << value.GetRadius());
}
Sputnik Sputnik::operator =(const Sputnik& v)
{
    if (this == &v) return *this;
    delete[] name;
    
    name = new char[strlen(v.name) + 1];
    strcpy_s(name, strlen(v.name) + 1, v.name);
 
    mass = v.mass;
    radius = v.radius;
    return *this;
}
Sputnik ::~Sputnik()
{
    delete[]name;
 
}
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
//Galaxy.h
#pragma once
#include"Star.h"
#include<assert.h>
#include<ostream>
class Galaxy
{
private:
    int date;
    int length;
    Star* stars;
public:
    int Get_Date() ;
    void Set_Date(int value);
    int Get_Length();
    void Set_Length(int value);
    Star& operator[](const int index);
    Galaxy operator =(const Galaxy& v);
    Galaxy();
    
    Galaxy( int _length);
    Galaxy(int _data, Star* _satrs);
    ~Galaxy();
};
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
//Galaxy.cpp
#include "Galaxy.h"
#include"Star.h"
#include<iostream>
#include<assert.h>
#include<ostream>
using namespace std;
Galaxy::Galaxy()
{
 
    stars = new Star[0];
    length = 0;
    date = 0;
}
void Galaxy::Set_Date(int value)
{
    date = value;
}
int Galaxy::Get_Date()
{
    return date;
}
void Galaxy::Set_Length(int value)
{
    length = value;
}
int Galaxy::Get_Length()
{
    return length;
}
Star& Galaxy::operator[](const int index)
{
    return stars[index];
}
 
Galaxy::Galaxy( int _length)
{
  stars = new Star[_length];
    
}
 
Galaxy Galaxy::operator =(const Galaxy& v)
{
    if (this == &v) return *this;
    stars = new Star[v.length];
    this->stars->SetDiapasone(v.stars->GetDiapasone());
    this->stars->SetTemp(v.stars->GetTemp());
    this->stars->SetTime(v.stars->GetTime());
    return *this;
}
 
Galaxy::Galaxy(int _data, Star*_stars )
{
    date = _data;
    stars->SetDiapasone(_stars->GetDiapasone());
    stars->SetName(_stars->GetName());
    stars->SetSpt(_stars->GetSpt());
    stars->SetTemp(_stars->GetTemp());
    stars->SetTime(_stars->GetTime());
    stars->SetWay(_stars->GetWay());
}
 
Galaxy::~Galaxy()
{
    delete[]stars;
}
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
//Main
#include"Planet.h"
#include"Star.h"
#include"Galaxy.h"
#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    cout << "Введите имя" << endl;
    char* name = new char[10];
    cin >> name;
    Sputnik sp(name, 12, 3);
    Star star(12,3,1,name,4,sp);
    Star star2(34, 5, 6, name, 12, sp);
    Star star3(66, 89, 99, name, 5555, sp);
    Galaxy gal(3);
    gal[0] = star;
    gal[1] = star2;
    gal[2] = star3;
    for (int i = 0; i < 3;i++)
    {
        cout << gal[i] << endl;
        
    }
    cin.get();
    cin.get();
    return 0;
}
Миниатюры
Что не так в перегрузке оператора индексирования?  
0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 18:06  [ТС]
Работает
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 18:17
Цитата Сообщение от Макрой Посмотреть сообщение
Galaxy Galaxy::operator =(const Galaxy& v)
тут по прежнему нет освобождения ресурсов, и я же говорил вам про возврат ссылки
Цитата Сообщение от Макрой Посмотреть сообщение
Galaxy::Galaxy(int _data, Star*_stars )
Это вообще непонятно что за конструктор, в котором даже выделения ресурсов нет.
1
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 20:54  [ТС]
Цитата Сообщение от zayats80888 Посмотреть сообщение
тут по прежнему нет освобождения ресурсов, и я же говорил вам про возврат ссылки
C++
1
2
3
4
5
6
7
8
delete[]stars;
if (this == &v) return *this;
    stars = new Star[v.length];
    
    this->stars->SetDiapasone(v.stars->GetDiapasone());
    this->stars->SetTemp(v.stars->GetTemp());
    this->stars->SetTime(v.stars->GetTime());
    return *this;
Цитата Сообщение от zayats80888 Посмотреть сообщение
Это вообще непонятно что за конструктор, в котором даже выделения ресурсов нет.
C++
1
2
3
4
5
6
7
8
stars = new Star[length];
    date = _data;
    stars->SetDiapasone(_stars->GetDiapasone());
    stars->SetName(_stars->GetName());
    stars->SetSpt(_stars->GetSpt());
    stars->SetTemp(_stars->GetTemp());
    stars->SetTime(_stars->GetTime());
    stars->SetWay(_stars->GetWay());
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 20:59
Цитата Сообщение от Макрой Посмотреть сообщение
stars = new Star[length];
* * date = _data;
* * stars->SetDiapasone(_stars->GetDiapasone());
* * stars->SetName(_stars->GetName());
* * stars->SetSpt(_stars->GetSpt());
* * stars->SetTemp(_stars->GetTemp());
* * stars->SetTime(_stars->GetTime());
* * stars->SetWay(_stars->GetWay());
это по прежнему трэш, length не инициализирована, объясните что вы хотите туда передавать.
1
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 21:01  [ТС]
lenght - размер массива типа Star
C++
1
Galaxy gal(3);
C++
1
2
3
4
5
Galaxy::Galaxy( int _length)
{
  stars = new Star[_length];
    
}
C++
1
2
3
4
5
6
7
8
gal[0] = star;
gal[1] = star2;
gal[2] = star3;
for (int i = 0; i < 3;i++)
    {
        cout << gal[i] << endl;
        
    }
0
23.07.2019, 21:02

Не по теме:

Цитата Сообщение от zayats80888 Посмотреть сообщение
это по прежнему трэш
с указателем на массив так вообще нельзя. Нужно в цикле пройти и присвоить. Или констрстуировать иначе (С++11).

0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 21:02  [ТС]
zayats80888, Вот
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 21:03
Цитата Сообщение от Макрой Посмотреть сообщение
Galaxy gal(3);
Это другой конструктор, мы говорим про Galaxy(int _data, Star* _satrs);
0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 21:03  [ТС]
zayats80888,
В этом конструкторе я инициализирую массив Star и переменную date
0
 Аватар для zayats80888
6352 / 3523 / 1428
Регистрация: 07.02.2019
Сообщений: 8,995
23.07.2019, 21:06
Цитата Сообщение от Макрой Посмотреть сообщение
я инициализирую массив Star и переменную date
А length кто инициализировать будет? Star* _satrs вы сюда массив звезд передаете или указатель на одну звезду?(что в целом не важно, но если второе, то лучше по ссылке)
0
64 / 45 / 20
Регистрация: 04.12.2018
Сообщений: 334
23.07.2019, 21:14  [ТС]
zayats80888, теперь проинициализировал

C++
1
2
3
4
5
6
Galaxy::Galaxy( int _length)
{
  length = _length;
  stars = new Star[_length];
    
}
Теперь все правильно ?
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
23.07.2019, 21:14

Перегрузка оператора индексирования для <map>
Вопрос: как правильно перегрузить оператор для контейнера map, который принадлежит к классу? Заранее спасибо! class TrainStation ...

Аналог перегрузки оператора индексирования (operator [])
Как по-другому(то есть в виде обычной функции или как то ещё) можно записать перегрузку оператора индексирования? Например в моём случае:...

Перегрузка оператора индексирования для контейнера list
Здравствуйте помогите перегрузить оператор индексирования для контейнера list это последнее задание из домашнего задания,преподователь...

Перегрузка оператора индексирования для обращения к элементам по имени
Доброго времени суток! Столкнулся с проблемой перегрузки оператора индексирования при разработке класса-массива. Обращение к элементам...

Ошибка в перегрузке оператора
Не пойму в чем дело(( Имеется класс вектор ,вычислил длину,а теперь очу сравнить их величины,но не могу составить данный оператор выдает...


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

Или воспользуйтесь поиском по форуму:
40
Ответ Создать тему
Новые блоги и статьи
GitDOS: Когда я решил скрестить MS-DOS, GitHub и Claude
MaGz GoLd 08.07.2026
Привет, Киберфорум! Хочу поделиться своим проектом, который, надеюсь, вас заинтересует. GitDOS — это веб-приложение, которое позволяет запускать DOS в браузере с тремя крутыми фичами: диски живут в. . .
Учебный мини "цифровой двойник" = (Сервер = Java + Flask_питон )+(3D = Гугловскаая 4T nvideo + google colab) +( WMS = Odoo на Docker)
anaschu 07.07.2026
Увидел в требованиях к вакансии создателя имитационных моделей связку (REst + Api + WMS + Anylogic + питон + 3D Nvideo), и решил посмотреть, что это такое. Из этого всего я работал более менее. . .
Море в объективе
kumehtar 06.07.2026
Хотел написать много проникновенных слов, но передумал. Оно само - говорит. Кто слышит тот слышит.
Doom для терминала без стрельбы и монстров. 3D Raycasting на ascii.
dcc0 05.07.2026
Попросил нейронную сеть deepai. org написать рейкастинг 3D с библиотекой ncurses для Linux. Чтобы можно было ходить на стрелочки. Чтобы стены были отрисованы символами. Справилась. Первый вариант. . .
Установка статуса документа по условию
Maks 05.07.2026
Алгоритм из решения ниже реализован на нетиповом документе "НарядПутевка" разработанного в КА2. Задача: в табличной части "Материалы" документа при записи автоматически устанавливать статус. . .
Сезонность и суточность закисления почв
anaschu 04.07.2026
200 часов это все равно моловато. Есть ситуации, но нестандартные, когда смена происходит за 5 лет. Но обычно это 50 лет и более. Наверное, закисление почвы происходит сезонно в средней. . .
В чем ценность человеческого опыта в глобальном смысле?
kumehtar 03.07.2026
Возможно, ценность человека не в том, что он однажды достигает мудрости, а в том, что он становится носителем карты пути. Он знает не только истину, но и последовательность внутренних изменений,. . .
интеграция AnyLogic с самописным REST API и переход на Odoo
anaschu 03.07.2026
Успешная интеграция AnyLogic с самописным REST API и переход на промышленную Odoo WMS Сегодня проделал огромный путь от простой симуляции физических процессов до построения полноценной. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru