С Новым годом! Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.91/11: Рейтинг темы: голосов - 11, средняя оценка - 4.91
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1

Перегрузка потокового оператора (<<). Выдает адрес вместо значения

26.07.2012, 13:49. Показов 2450. Ответов 4
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Сабж. Все компелится нормально. Если делать << void то работает ок см комменты
если делать класса std::ostream& то возвращает 16чное значение.
Заранее спасибо

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
#ifndef Point_HPP // anti multiply including gates
#define Point_HPP
 
#include <sstream>
    
 
class Point
{   
    private:        //  declaration of private data members 
    double x;       // X coordinate
    double y;       // Y coordinate
 
    public: // public declaration of data members (in given example haven't ) and member functions 
 
 
        //----------- Declaration of Constructors -----------//
    Point();                                    // Default constructor
    Point(double newX, double newY);            // Constructor 
    Point (const Point& ObjectOfClassPoint);    //COPY constructor
    ~Point(); // 
 
 
    //----------- Declaration of  Accessors member functions -----------//
 
    std::ostream& ToString() ; 
    //void Point::ToString () const; 
    
    
};
 
 
//----------- Implementaion of Global Ostream << Operator  -----------//
 
/*std::ostream& operator<< (std::ostream &out, Point &cPoint) 
{
    // SHOULD BE WITHOUT friendness 
    // Point's members directly.
    out << cPoint.ToString();
        
    return out;
}*/
 
#endif // Point_HPP
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
#include <iostream>
#include "Point.hpp"
 
 
 
 
int main()
 
    {
 
 
    std::cout << "\n\t ---TEST OF Operator Overloading--- \n";
    
    Point MyPoint(1455  , 1492  );                          // Creating an object of  Point using constructor 
    Point MySecondPoint (1517   , 1796  );                  // Creating an object of  Point using constructor 
    Point MyThirdPoint (1610  , 1882   );                   // Creating an object of  Point using constructor 
    MyPoint.ToString();
    MySecondPoint.ToString();
    std::cout << "\n";
 
 
    std::cout << "\n std::cout << MySecondPoint.ToString();;\n\n\n ";
    std::cout << "\n" <<  MySecondPoint.ToString();
 
 
    std::cout << "\n ---  Now some easy math --- ";
    
 
  return 0 ; 
}
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
#include "Point.hpp"
#include <iostream>
#include <sstream>
#include <cmath>
 
 
 
 
 
            //----------- Implementation of Constructors -----------//
 
Point::Point() : x(0), y(0)                                                         // Default constructor (implemented using colon syntax )
{ 
    std::cout << "hi my default constructor\n\n\t";
}                                       
Point::Point(double newX, double newY) : x(newX), y(newY)                           // Constructor 
{ 
    //std::cout << "hi my constructor\n\n\t"; 
}               
Point::~Point()                                                                     // Destructor
{
    //std::cout << "bye my point..\n";
}                                    
 
Point::Point (const Point& ObjectOfClassPoint)                                      // Copy constructor
        {
            //std::cout << "this is COPY constructor\n\n\t ";
            x = ObjectOfClassPoint.x;
            y = ObjectOfClassPoint.y;
 
        }
 
 
        
 
            //----------- Implementation of Accessor(s) member functions -----------//
 
std::ostream& Point::ToString ()
    
    {// Function ToString should also be const also because of reason of mistaken modification of an object's value 
        std::ostringstream os;                              // std::stringstream object
        os << " Point (" << x << ", " << y << ")\n";            // customization of output 
        os.str();                                           // str() function retrieve the string from the string buffer
        return os;
 
    }
 
 
/*void Point::ToString () const
    
    {// Function ToString should also be const also because of reason of mistaken modification of an object's value 
        std::ostringstream os;                              // std::stringstream object
        os << " Point (" << x << ", " << y << ")";          // customization of output 
        std::cout << os.str()<<"\n";                        // str() function retrieve the string from the string buffer
    }
    */
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
26.07.2012, 13:49
Ответы с готовыми решениями:

Выдает адрес вместо значения
Привет. Функция шоу эрэй должна отображать значения в массиве, но выдает адреса (помоему...). Где ошибка? Я сначала думал что дело в том,...

Перегрузка оператора сложения в классе выдает ошибку с деструктором
Здравствуйте, взял у Липманна программу, которую по заданию надо доработать. Ее смысл заключается в том, что объект класса (динамическая...

Cout пишет адрес вместо значения
cout пишет адрес вместо значения. Спасибо

4
Каратель
Эксперт С++
6610 / 4029 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
26.07.2012, 14:11
Цитата Сообщение от Leeto Посмотреть сообщение
std::ostream& Point::ToString ()
{// Function ToString should also be const also because of reason of mistaken modification of an object's value
std::ostringstream os; // std::stringstream object
os << " Point (" << x << ", " << y << ")\n"; // customization of output
os.str(); // str() function retrieve the string from the string buffer
return os;
}
C++
1
2
3
4
5
6
std::string Point::ToString ()
{// Function ToString should also be const also because of reason of mistaken modification of an object's value 
    std::ostringstream os;                        // std::stringstream object
    os << "Point (" << x << ", " << y << ")"; // customization of output 
    return os.str();                                  // str() function retrieve the string from the string buffer
}
Добавлено через 1 минуту
Цитата Сообщение от Leeto Посмотреть сообщение
std::ostream& operator<< (std::ostream &out, Point &cPoint)
C++
1
std::ostream& operator << (std::ostream &out, Point const& cPoint)
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
26.07.2012, 14:21  [ТС]
Цитата Сообщение от Jupiter Посмотреть сообщение
C++
1
2
3
4
5
6
std::string Point::ToString ()
{// Function ToString should also be const also because of reason of mistaken modification of an object's value 
    std::ostringstream os;                        // std::stringstream object
    os << "Point (" << x << ", " << y << ")"; // customization of output 
    return os.str();                                  // str() function retrieve the string from the string buffer
}
Добавлено через 1 минуту

C++
1
std::ostream& operator << (std::ostream &out, Point const& cPoint)


А как мне теперь сделать так чтобы сразу можно было объект MySecondPoint послать на cout <<
Компилятор выдает Link error

C++
1
2
3
4
5
6
7
8
9
std::ostream& operator<< (std::ostream &out, Point &cPoint) 
{
    // SHOULD BE WITHOUT friendness 
    // Point's members directly.
 
    out << cPoint.ToString();
        
    return out;
}
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
#include <iostream>
#include "Point.hpp"
 
 
 
 
int main()
 
    {
 
 
    std::cout << "\n\t ---TEST OF Operator Overloading--- \n";
    
    Point MyPoint(1455  , 1492  );                          // Creating an object of  Point using constructor 
    Point MySecondPoint (1517   , 1796  );                  // Creating an object of  Point using constructor 
    Point MyThirdPoint (1610  , 1882   );                   // Creating an object of  Point using constructor 
    MyPoint.ToString();
    MySecondPoint.ToString();
    std::cout << "\n";
 
 
    std::cout << "\n std::cout << MySecondPoint.ToString();;\n\n\n ";
    std::cout << "\n" <<  MySecondPoint.ToString();
 
 
    std::cout << "\n ---  Now some easy math --- ";
 
    std::cout << "\n MySecondPoint;\n\n\n ";
    std::cout << MySecondPoint;
    
 
  return 0 ; 
}
PS В этом задании нельзя френдить и надо использовать ToString() и надо чтобы operator << be Global но реализован внутри hpp


1>Point.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class Point &)" (??6@YAAAV?$basic_ostream@DU?$char_trait s@D@std@@@std@@AAV01@AAVPoint@@@Z) already defined in main.obj

fatal error LNK1169: one or more multiply defined symbols found
0
Каратель
Эксперт С++
6610 / 4029 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
26.07.2012, 14:54
point.hpp
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
#ifndef Point_HPP // anti multiply including gates
#define Point_HPP
 
#include <ostream>
#include <string>
    
class Point
{   
private:        //  declaration of private data members 
    double x;       // X coordinate
    double y;       // Y coordinate
 
public: // public declaration of data members (in given example haven't ) and member functions 
 
        //----------- Declaration of Constructors -----------//
    Point();                                    // Default constructor
    Point(double newX, double newY);            // Constructor 
    Point (const Point& ObjectOfClassPoint);    //COPY constructor
    ~Point(); // 
 
    //----------- Declaration of  Accessors member functions -----------//
    std::string ToString() const;    
};
 
 
//----------- Declaration of Global Ostream << Operator  -----------//
 
std::ostream& operator<< (std::ostream& out, Point const& cPoint); 
 
#endif // Point_HPP


Добавлено через 19 секунд

point.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
46
#include "Point.hpp"
 
#include <iostream>
#include <sstream>
#include <cmath> 
  
            //----------- Implementation of Constructors -----------//
 
Point::Point() : x(0), y(0)                                                         // Default constructor (implemented using colon syntax )
{ 
    std::cout << "hi my default constructor\n\n\t";
}     
 
Point::Point(double newX, double newY) : x(newX), y(newY)                           // Constructor 
{ 
    //std::cout << "hi my constructor\n\n\t"; 
}
 
Point::~Point()                                                                     // Destructor
{
    //std::cout << "bye my point..\n";
}                                    
 
Point::Point (const Point& ObjectOfClassPoint)                                      // Copy constructor
{
    //std::cout << "this is COPY constructor\n\n\t ";
    x = ObjectOfClassPoint.x;
    y = ObjectOfClassPoint.y;
}
 
            //----------- Implementation of Accessor(s) member functions -----------//
 
std::string Point::ToString() const
{
    // Function ToString should also be const also because of reason of mistaken modification of an object's value 
    std::ostringstream os;                              // std::stringstream object
    os << " Point (" << x << ", " << y << ")\n";        // customization of output 
    return os.str();                                    // str() function retrieve the string from the string buffer
}
 
std::ostream& operator << (std::ostream& out, Point const& cPoint)
{
    // SHOULD BE WITHOUT friendness 
    // Point's members directly.
    return (out << cPoint.ToString());
}

Добавлено через 20 секунд

main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "Point.hpp"
 
int main()
{
    std::cout << "\n\t ---TEST OF Operator Overloading--- \n";
    
    Point MyPoint(1455, 1492);                          // Creating an object of  Point using constructor 
    Point MySecondPoint (1517, 1796);                  // Creating an object of  Point using constructor 
    Point MyThirdPoint (1610, 1882);                   // Creating an object of  Point using constructor 
    
    std::cout << MyPoint << std::endl
        << MySecondPoint << std::endl
        << MyThirdPoint  << std::endl;
 
  return 0 ; 
}
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
26.07.2012, 15:38  [ТС]
Цитата Сообщение от Jupiter Посмотреть сообщение
point.hpp
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
#ifndef Point_HPP // anti multiply including gates
#define Point_HPP
 
#include <ostream>
#include <string>
    
class Point
{   
private:        //  declaration of private data members 
    double x;       // X coordinate
    double y;       // Y coordinate
 
public: // public declaration of data members (in given example haven't ) and member functions 
 
        //----------- Declaration of Constructors -----------//
    Point();                                    // Default constructor
    Point(double newX, double newY);            // Constructor 
    Point (const Point& ObjectOfClassPoint);    //COPY constructor
    ~Point(); // 
 
    //----------- Declaration of  Accessors member functions -----------//
    std::string ToString() const;    
};
 
 
//----------- Declaration of Global Ostream << Operator  -----------//
 
std::ostream& operator<< (std::ostream& out, Point const& cPoint); 
 
#endif // Point_HPP


Добавлено через 19 секунд

point.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
46
#include "Point.hpp"
 
#include <iostream>
#include <sstream>
#include <cmath> 
  
            //----------- Implementation of Constructors -----------//
 
Point::Point() : x(0), y(0)                                                         // Default constructor (implemented using colon syntax )
{ 
    std::cout << "hi my default constructor\n\n\t";
}     
 
Point::Point(double newX, double newY) : x(newX), y(newY)                           // Constructor 
{ 
    //std::cout << "hi my constructor\n\n\t"; 
}
 
Point::~Point()                                                                     // Destructor
{
    //std::cout << "bye my point..\n";
}                                    
 
Point::Point (const Point& ObjectOfClassPoint)                                      // Copy constructor
{
    //std::cout << "this is COPY constructor\n\n\t ";
    x = ObjectOfClassPoint.x;
    y = ObjectOfClassPoint.y;
}
 
            //----------- Implementation of Accessor(s) member functions -----------//
 
std::string Point::ToString() const
{
    // Function ToString should also be const also because of reason of mistaken modification of an object's value 
    std::ostringstream os;                              // std::stringstream object
    os << " Point (" << x << ", " << y << ")\n";        // customization of output 
    return os.str();                                    // str() function retrieve the string from the string buffer
}
 
std::ostream& operator << (std::ostream& out, Point const& cPoint)
{
    // SHOULD BE WITHOUT friendness 
    // Point's members directly.
    return (out << cPoint.ToString());
}

Добавлено через 20 секунд

main.cpp
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include "Point.hpp"
 
int main()
{
    std::cout << "\n\t ---TEST OF Operator Overloading--- \n";
    
    Point MyPoint(1455, 1492);                          // Creating an object of  Point using constructor 
    Point MySecondPoint (1517, 1796);                  // Creating an object of  Point using constructor 
    Point MyThirdPoint (1610, 1882);                   // Creating an object of  Point using constructor 
    
    std::cout << MyPoint << std::endl
        << MySecondPoint << std::endl
        << MyThirdPoint  << std::endl;
 
  return 0 ; 
}

Спасибо большое !
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
26.07.2012, 15:38
Помогаю со студенческими работами здесь

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

Массив вместо своего значения выдает М
Задание: определить количество положительный и отрицательных чисел, но когда показывается массив там во всех ячейках стоит М ...

Вместо значения из таблицы выдает значение параметра запроса
Пытаюсь получить данные из базы. Если передавать в запрос параметры: public client() { ...

Перегрузка потокового ввода-вывода
Доброго времени суток!!! Возникла такая проблема: необходимо сделать перегрузку операций &lt;&lt; и &gt;&gt;. Вот что у меня есть: ...

Перегрузка потокового ввода/вывода
Вот сама перегрузка ostream&amp; operator&lt;&lt; (ostream&amp; out, Poli&amp; outstream) { out&lt;&lt;&quot;Степень полинома=&quot;&lt;&lt;outstream.n&lt;&lt;endl; ...


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

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Новые блоги и статьи
сукцессия микоризы: основная теория в виде двух уравнений.
anaschu 11.01.2026
https:/ / rutube. ru/ video/ 7a537f578d808e67a3c6fd818a44a5c4/
WordPad для Windows 11
Jel 10.01.2026
WordPad для Windows 11 — это приложение, которое восстанавливает классический текстовый редактор WordPad в операционной системе Windows 11. После того как Microsoft исключила WordPad из. . .
Classic Notepad for Windows 11
Jel 10.01.2026
Old Classic Notepad for Windows 11 Приложение для Windows 11, позволяющее пользователям вернуть классическую версию текстового редактора «Блокнот» из Windows 10. Программа предоставляет более. . .
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и источниками (напряжения, ЭДС и тока). Найти токи и напряжения во всех элементах. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru