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

boost/shared_ptr (Smart Pointers)

09.08.2012, 13:21. Показов 2142. Ответов 3
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Допустим есть проект

Array_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//                                                      
//                                                  (---.Array_hpp---)
//
#ifndef Array_HPP   // Preprocessor gates
#define Array_HPP
 
    #include <sstream>
    #include <iostream>
    #include <string>       // need also for ArrayException.hpp
    #include "ArrayException.hpp"
 
    template <class T>  //Remove the "=double" default parameter.
    class Array
        {
    
            protected:              // Declaration of private data members 
             unsigned int m_size;
             
              T*           m_data;          //m_data should be a pointer, since you want to allocate data to it
 
            public:                 // Public declaration of data members (in given example haven't ) and member functions 
                static int m_size_default;
                unsigned int array_stack_index; 
                //----------- Declaration of Constructors -----------//
              Array();                                  // Default constructor
              Array(const unsigned int new_size);       // Constructor 
              Array( Array<T>& ObjArray);               // Copy constructor
              ~Array();                                 // Destructor
 
               //----------- Declaration of Modificator(s) member functions -----------//
              void SetElement(const T& ObjType,const  unsigned int index);
              static void DefaultSize( int newSize) ;
 
              //----------- Declaration of  Accessors member functions -----------//
              T& GetElement(const unsigned int index) ;
              static int  DefaultSize() ;
              unsigned int Size() const;
              unsigned int ArrayCurrentIndex();
              
 
              //----------- Declaration of Operators Overloading the class's members -----------//
              Array<T>& operator    =   (const Array& ObjArray);                //Const correctness here.
              const T& operator  [] (unsigned int index) const;
              T& operator       []  (unsigned int index);           
        };
 
    #ifndef Array_cpp // Must be the same name as in source file #define
 
        #include "Array.cpp"
 
    #endif //#ifndef Array_cpp is CLOSED
 
#endif //  #ifndef Array_HPP is CLOSED


ArrayException_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
31
32
33
34
35
36
37
38
39
40
//                                                      
//                                                  (---.ArrayException_hpp---)
//
#ifndef ArrayException_HPP
#define ArrayException_HPP
 
    #include <iostream>
    #include <string>
    using namespace std;
 
    class ArrayException 
    {
    public : 
        ArrayException(){};
        virtual std::string GetMessage() const = 0;
    };  
 
    class OutOfBoundsException : public ArrayException
    {
    private : 
         int array_index;
    public : 
        OutOfBoundsException();
        OutOfBoundsException(int index) : array_index(index) {}
        std::string GetMessage() const
        
        {
 
        std::ostringstream os;      // std::stringstream object
                    os  <<  "\nEXCEPTION HANDLING ERROR: "
                        << "the given element " 
                        << "with index : " 
                        << array_index 
                        << " is out of bounds\n "   ;
 
                    return os.str();    
        }
 
    };
#endif // ArrayException_H


Circle_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
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
//                                                      
//                                                  (---.Circle_hpp---)
//
#ifndef Circle_HPP 
// anti multiply including gates
#define Circle_HPP
#define _USE_MATH_DEFINES 
 
// lib(s)
#include <iostream>
 
// Header(s) of depended classes 
#include "Point.hpp"
 
// Header(s) of ABC 
#include "Shape.hpp"
 
 
 
 
class Circle : public Shape
{
private :               
    //  declaration of private data members 
    
    Point CentralPoint;
    Point RadiusPoint; 
 
public :                
    // public declaration of data members 
    // (in given example haven't ) and member functions 
    
    
 
    //----------- Declaration of Constructors -----------//
    Circle();
    Circle (const Point& CentralPoint,const Point& RadiusPoint) ; 
    Circle (const Circle  &ObjLine); 
    ~Circle ();
 
    //----------- Declaration of  Accessors member functions -----------//
    Point Central_Point() const;
    Point Radius_Point() const;
    std::string ToString() const;    
    /*virtual*/ void Draw() const { std::cout << "This's  Circle from Draw()\n"; }
 
    //----------- Declaration of  Modificators member functions -----------//
    Point& Central_Point(const Point  &ObjPoint);
    Point& Radius_Point(const Point  &ObjPoint);
 
 
    //----------- Declaration of Calculators (additional functionality) member functions -----------//
    double Radius() const; 
    double Diameter() const;
    double Area() const;
    double Circumference() const;
 
    //----------- Declaration of Operators Overloading the class's members -----------//
 
        Circle& operator = (const Circle& ObjCircle);                   // Assignment operator.
 
        //----------- Declaration of Global Ostream << Operator  -----------//
 
    friend std::ostream& operator<< (std::ostream& out,const Circle & ObjCircle); 
 
}   /*!!!*/ ; /*!!!*/ 
 
 
 
#endif // Circle_HPP


Line_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
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
//                                                      
//                                                  (---.Line_hpp---)
//
#ifndef Line_HPP 
// anti multiply including gates
#define Line_HPP
 
// lib(s)
#include <iostream>
 
// Header(s) of depended classes 
#include "Point.hpp"
 
// Header(s) of ABC 
#include "Shape.hpp"
 
 
class Line : public Shape
{
private :               
    //  declaration of private data members 
    
    Point StartPoint;
    Point EndPoint; 
 
public :                
    // public declaration of data members (in given example haven't ) and member functions 
 
 
    //----------- Declaration of Constructors -----------//
    Line();
    Line (const  Point& NewStartPoint,const Point& NewEndPoint) ; 
    Line (const Line  &ObjLine); 
    ~Line ();
 
    //----------- Declaration of  Accessors member functions -----------//
    Point Start() const;
    Point End() const;
    std::string ToString() const;   
    /*virtual*/ void Draw() const { std::cout << "This's  Line from Draw()\n"; }
 
 
    //----------- Declaration of  Modificators member functions -----------//
    Point& Start(const Point  &ObjPoint);
    Point& End(const Point  &ObjPoint);
 
 
    //----------- Declaration of Calculators (additional functionality) member functions -----------//
    double Length() const; 
 
    //----------- Declaration of Operators Overloading the class's members -----------//
 
    Line& operator = (const Line& ObjLine)      ;                   // Assignment operator.         
 
    //----------- Declaration of Global Ostream << Operator  -----------//
 
    friend std::ostream& operator<< (std::ostream& out,const Line & ObjLine); 
 
}   /*!!!*/ ; /*!!!*/ 
 
 
 
#endif // Line_HPP


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
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
//                                                      
//                                                  (---.Point_hpp---)
//  
#ifndef Point_HPP 
// anti multiply including gates
#define Point_HPP
 
// Lib(s)
#include <string>
#include <iostream>
#include <sstream>
#include <cmath>
 
// Header(s) of ABC 
#include "Shape.hpp"
 
class Point : public Shape
{   
    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(const double newX ,const double newY) ;           // Constructor 
    explicit Point(const double value );                    // Second Constructor 
    Point (const Point& ObjectOfClassPoint);                //COPY constructor
    ~Point(); // 
 
 
    //----------- Declaration of  Accessors member functions -----------//
    std::string ToString() const;    
    double X() const;                   
    double Y() const;   
    /*virtual*/ void Draw() const { std::cout << "This's  Point from Draw()\n"; }
 
 
    //----------- Declaration and  of and Implementaion of setters member functions -----------//
    void X(const double newX) {x = newX;};  // The x-coordinate
    void Y(const double newY) {y = newY;};  // The y-coordinate
 
 
    //----------- Declaration of Calculators (additional functionality) member functions -----------//
    double Distance() const;
    double Distance(  const Point  & ObjPoint ) const;
 
 
    //----------- Declaration of Operators Overloading the class's members -----------//
    Point  operator -  () const;                                    // Negate the coordinates.
    Point  operator *  (double factor) const;                       // Scale the coordinates.
    Point  operator +  (const Point& ObjPoint) const;               // Add coordinates.
    bool   operator == (const Point& ObjPoint) const;               // Equally compare operator.
    Point& operator =  (const Point& ObjPoint);                 // Assignment operator.
    Point& operator *= (double factor );                        // Scale the coordinates & assign.
    Point& operator += (const Point& ObjPoint);
    Point& operator -= (const Point& ObjPoint);
 
 
    //----------- Declaration of Global Ostream << Operator  -----------//
    friend std::ostream& operator << (std::ostream& out,const Point & ObjPoint); 
    
};
 
//----------- Implementaion (inline) of getters member functions -----------//
// Given functions should be const because we not willing modify contained variables when we call those fucntions in any case
inline  double Point::X() const {return x;};                    
inline  double Point::Y() const {return y;};    
 
 
#endif // Point_HPP


Shape_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
31
32
33
34
35
36
37
38
39
40
41
// 
//                                                  (---.Shape_hpp---)
//
#ifndef Shape_HPP
// anti multiply including gates
#define Shape_HPP
 
// Lib(s)
#include <iostream>
#include <sstream>
#include <string>
 
class Shape
 
    {
    private: 
        int id; 
    public: 
    
            //----------- Declaration of Constructors -----------//
        Shape(); 
        Shape(const Shape &ObjShape); 
        virtual ~Shape () ;
        
 
            //----------- Declaration of  Accessors member functions -----------//
        virtual std::string ToString() const;
        virtual void Draw() const = 0 {std::cout << "some text"<< "\n"; }
        int ID();
        void Print ()  
            {   
                std::cout << ToString();
            }   
 
            //----------- Declaration of Global(friend) Ostream << Operator  -----------//
        friend std::ostream& operator << (std::ostream& out,const Shape & ObjPoint); 
 
    };
 
 
#endif


Array_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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//                                                      
//                                                  (---.Array_CPP---)
//  
    #ifndef Array_CPP   // Preprocessor gates
    #define Array_CPP
 
        #include "Array.hpp"
        
 
        template <class T>
        int Array<T>::m_size_default = 10;
 
                    //----------- Implementation of Constructors -----------//
        template <class T>
        Array<T>::Array() :  m_size(m_size_default), m_data(new T[m_size]), array_stack_index(0)                                    
            {
            //  std::cout << "Array Default Constructor was called " ;
            }
 
        template <class T>
        Array<T>::Array(const unsigned int new_size) : m_size(new_size), m_data(new T[new_size]), array_stack_index(0)        
            {    //specified by the size input argument                 
            //  std::cout << "Array Constructor was called "; 
            }
 
        template <class T>
        Array<T>::Array( Array& ObjArray)
            {
                 // std::cout << "Array copy Constructor "; 
                m_size    =    ObjArray.m_size;         // shallow copy - this is not dynamic alloc
                array_stack_index = ObjArray.array_stack_index;
                if (ObjArray.m_data)                    // if not zeros then there is a ref. - Deep copy needed
                    {
                        m_data = new T[ObjArray.m_size];
                        for (unsigned int i = 0; i <   ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];
                    }
                else
                m_data = 0;                             //NULL
            }
 
        template <class T>
        Array<T>::~Array()
            {
                std::cout << "\n *Array Destructor was called*" ;
                delete [] m_data;
            }
 
        //----------- Implementaion of Modificator(s) member(s) function -----------//
        template <class T> 
        void Array<T>::SetElement(const T& ObjType,const unsigned int index)
            {
                array_stack_index = index; 
                    std::cout << "Set Element[" << index << "]<-  "; 
                    if (array_stack_index >= m_size || array_stack_index < 0 )
                        {   
                            std::cout << " Data wasn't setted"; 
                            throw OutOfBoundsException(array_stack_index--);
                        }
                    std::cout << ObjType << "\n"; 
                    m_data[array_stack_index] = ObjType;
            }
 
        template <typename T>
        void Array<T>::DefaultSize( int newSize) 
            { 
                m_size_default = newSize; 
            }
 
        //----------- Implementation of Accessor(s) member functions -----------//
        template <class T> 
        T& Array<T>::GetElement(const unsigned int index) 
            {
                array_stack_index = index; 
                //std::cout << "GetElement[" << index <<"] ->" ;
                    if (array_stack_index >= m_size || array_stack_index < 0)
                        {       
                            std::cout << " Data wasn't getted"; 
                            throw OutOfBoundsException(array_stack_index++);
                        }
 
                return m_data[array_stack_index];
            }
 
        template <typename T>
        int Array<T>::DefaultSize() 
            { 
                return m_size_default;
            }
 
        template<class T>
        unsigned int Array<T>::Size() const
        {
            
            return this->m_size; 
        }
 
        template<class T>
        unsigned int  Array<T>::ArrayCurrentIndex()
            {
                return this->array_stack_index; 
            }
 
        //----------- Implementation of Operators Overloading the class's member -----------//
 
        template <class T>
        Array<T>& Array<T>::operator = (const Array& ObjArray)
            {
             // std::cout << " Array Assignment operator\n";
            if (this == &ObjArray)
                {
                    //std::cout << "Same Array \n"; 
                    return *this;
                }
 
            delete [] m_data;
            // std::cout << "Deleted m_data array\n";
 
            m_size = ObjArray.m_size;       // shallow copy - this is not dynamic alloc
 
            if (ObjArray.m_data)            // if not zeros then there is a ref.
                    {
                        // std::cout <<"im here\n"; 
 
                        m_data = new T[ObjArray.m_size];        // create a new pointee.
 
                        for (unsigned int i = 0; i <    ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];   //copy the points from/to array
                    }
            else
                m_data = 0;  //NULL
 
            return *this;
            }
 
        template <class T> 
        T& Array<T>::operator [] (unsigned int index) 
            {
                //std::cout << "Array [] operator" << std::endl;
                array_stack_index = index; 
                if (array_stack_index >= this->m_size)
                        { 
                            throw OutOfBoundsException(index);
                        }
                return m_data[index];
            }
 
        template <class T> 
        const T& Array<T>::operator [] (unsigned int index) const
        {   
            array_stack_index = index; 
            //std::cout << "const Array [] operator" << std::endl;
            if (array_stack_index > this-> m_size)
                        { 
                            throw OutOfBoundsException(array_stack_index);
                        }
            return m_data[array_stack_index];
        }
 
    #endif //Array_CPP


Circle_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
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
97
98
99
100
101
102
103
104
105
106
107
//                                                      
//                                                  (---.Circle_cpp---)
//
#include "Circle.hpp"
 
unsigned int  number_of_circle_destructor_calls = 1; 
    
//----------- Implementation of Constructors -----------//
 
    Circle::Circle():CentralPoint(0,0), RadiusPoint(0,0) {}
        
 
    Circle::Circle (const Point& NewCentralPoint,const Point& NewRadiusPoint)
        : CentralPoint(NewCentralPoint),RadiusPoint(NewRadiusPoint) {}
 
    Circle::Circle (const Circle  &ObjCircle) 
            {
                CentralPoint = ObjCircle.CentralPoint;
                RadiusPoint = ObjCircle.RadiusPoint; 
            }
    Circle::~Circle () 
        {
            std::cout   << "\n My Circle destructor was called " 
                        << number_of_circle_destructor_calls++ << " times " 
                        << ""; 
        }
 
    //----------- Implementation of  Accessors member functions -----------//
 
    
 
    Point Circle::Central_Point() const     
        { 
            return CentralPoint;
        }
    Point Circle::Radius_Point()    const   
        {
            return RadiusPoint;
        }
    
    std::string Circle::ToString() const
        {
                std::string s = Shape::ToString();  
                std::ostringstream os;                              
                // std::stringstream object
                os  << "Circle"
                    << "\nC.P.:"     << CentralPoint.ToString() 
                    << "\nR.P.:"     << RadiusPoint.ToString() 
                    << "\nC."                << s;                  
                // customization of output and calling base class functuanality 
                return os.str();                                    
                // str() function retrieve the string from the string buffer
        }
 
    //----------- Implementation of  Modificators member functions -----------//
    Point& Circle::Central_Point(const Point  & ObjPoint)
            {
                return CentralPoint = ObjPoint;
            }
 
    Point& Circle::Radius_Point(const Point  & ObjPoint)
            {
            return RadiusPoint = ObjPoint;
            }
 
 
    //----------- Implementation of Calculators (additional functionality) member functions -----------//
    double Circle::Radius() const
            {
                return CentralPoint.Distance(RadiusPoint); 
            }
 
    double Circle::Diameter() const
        {
        return 2*Radius(); 
        }
 
    double Circle::Area() const
        {
        return M_PI*std::pow(Radius(),2); 
        }
    double Circle::Circumference() const
        {
        return 2*M_PI*Radius() ;
        }
 
    //----------- Implementation of Operators Overloading the class's member -----------//
 
    Circle& Circle::operator = (const Circle& ObjCircle)            
        // Assignment operator.         
        {
                //std::cout << "\n*My assignment CIRCLE operator was called*\n";
 
                        CentralPoint=ObjCircle.CentralPoint;
                        RadiusPoint=ObjCircle.RadiusPoint;
 
                 return *this ;
        }
 
    std::ostream& operator << (std::ostream& out,const Circle & ObjCircle)
                {
 
                    return out << "\nCentral Point: (" << ObjCircle.CentralPoint 
                               << " )\nPoint on the Circle: (" 
                               << ObjCircle.RadiusPoint << ")" ; 
     
                }


Line_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
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
//                                                      
//                                                  (---.Line_cpp---)
//
#include "Line.hpp"
 
 
unsigned int number_of_line_destructor_calls = 1; 
 
//----------- Implementation of Constructors -----------//
 
    Line::Line():StartPoint(0,0), EndPoint(0,0) {}
        
 
    Line::Line (const Point& NewStartPoint,const Point& NewEndPoint): StartPoint(NewStartPoint),EndPoint(NewEndPoint)
    {
    //   StartPoint =  NewStartPoint  ; 
    //   EndPoint   =  NewEndPoint  ; 
    }
 
    Line::Line (const Line  &ObjLine) 
            {
                StartPoint = ObjLine.StartPoint;
                EndPoint = ObjLine.EndPoint; 
            }
    Line::~Line () 
        {
            std::cout   << "\n My Line destructor was called " 
                        << number_of_line_destructor_calls++ << " times " 
                        << ""; 
        }
 
    //----------- Implementation of  Accessors member functions -----------//
    Point Line::Start() const   
        { 
            return StartPoint;
        }
    Point Line::End()   const   
        {
            return EndPoint;
        }
    
    
 
    std::string Line::ToString() const
            {
                std::string obj_string_from_shape = Shape::ToString();  
                std::ostringstream os;                              // std::stringstream object
                os  << "Line"
                    <<  "\nP1:"     << StartPoint.ToString() 
                    <<  "\nP2:"     << EndPoint.ToString() 
                    <<  "\nL."      << obj_string_from_shape ;                      // customization of output and calling base class functuanality 
                return os.str();                                    // str() function retrieve the string from the string buffer
            }
    //----------- Implementation of  Modificators member functions -----------//
    Point& Line::Start(const Point  & ObjPoint)
            {
                return StartPoint = ObjPoint;
            }
 
    Point& Line::End(const Point  & ObjPoint)
            {
            return EndPoint = ObjPoint;
            }
 
 
    //----------- Implementation of Calculators (additional functionality) member functions -----------//
    double Line::Length() const
            {
                return StartPoint.Distance(EndPoint); 
            }
 
    //----------- Implementation of Operators Overloading the class's member -----------//
 
    Line& Line::operator = (const Line& ObjLine)            // Assignment operator.         
        {
            //  std::cout << "\n*My assignment LINE operator was called*\n";
 
                StartPoint=ObjLine.StartPoint;
                EndPoint=ObjLine.EndPoint;
 
                    return *this ; 
        }
 
 
        //----------- Implementation of GLOBAL friend  << Operator  -----------//
 
    std::ostream& operator << (std::ostream& out,const Line & ObjLine)
            {
                
                return out << "P1(" << ObjLine.StartPoint 
                           << " ) , P2(" << ObjLine.EndPoint << ") "; 
            }


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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
//                                                      
//                                                  (---.Point_cpp---)
//  
    #include "Point.hpp"
 
 int number_of_point_constructor_calls          = 1 ;   
 int number_of_point_destructor_calls           = 1 ;  
 int number_of_point_assignment_operator_calls  = 1 ; 
 
 
            //----------- 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(const double newX ,const double newY) : x(newX)  , y(newY)     // Constructor 
        { 
    //      std::cout << " My Point constructor was called " << number_of_point_constructor_calls++ << " times " << "\n"; 
        }                   
 
Point::Point(const double value ) : x(value)                                        // Second Constructor 
        { 
        //std::cout << "hi my constructor\n\n\t"; 
        }   
Point::~Point()                                                             // Destructor
        {
            std::cout   << "\n My Point destructor was called " 
                        << number_of_point_destructor_calls++ << " times " 
                        << ""; 
        }                                    
 
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
        {
            std::string obj_string_from_shape = Shape::ToString();                              
            std::ostringstream os;                                  // std::stringstream object
            os << " P(" << x << ", " << y << ")P." 
               << obj_string_from_shape;                            // customization of output and calling base class functuanality 
            return os.str();                                        // str() function retrieve the string from the string buffer
        }
 
 
            //----------- Implementation of Calculators (additional functionality) member functions -----------//
double  Point::Distance() const
 
        {
            return std::sqrt(pow(x,2) + pow(y,2));
        }
 
 
double  Point::Distance(const Point   &ObjPt ) const
    
        {
            return std::sqrt(pow((x-ObjPt.x),2) + pow(y - ObjPt.y,2)); 
        }
 
 
            //----------- Implementation of Operators Overloading the class's member -----------//
    Point Point::operator  -  () const                                  // Negate the coordinates.          
        {
            return Point(-x,-y);
        }
 
    Point Point::operator  *  (double factor) const                     // Scale the coordinates.
        {
            return Point(x * factor, y * factor);
        }
 
    Point Point::operator  +  (const Point& ObjPoint) const             // Add coordinates.
        { 
            return Point(x + ObjPoint.x, y + ObjPoint.y);
        }
 
    bool Point::operator   == (const Point& ObjPoint) const             // Equally compare operator.    
        {
            return (x==ObjPoint.x)&(y==ObjPoint.y);
        }
 
    Point& Point::operator =  (const Point& ObjPoint)                           // Assignment operator.             
                {       
            //      std::cout << " My Point assignment operator was called " << number_of_point_assignment_operator_calls++ << " times " << "\n"; 
                    x=ObjPoint.x, y=ObjPoint.y;
                    return *this;                                               // The meaning of *this explained in this example (implementation) see comment out  
                }
 
    Point& Point::operator *= (double factor)                                   // Scale the coordinates & assign.      
        {
            x *= factor; 
            y *= factor;
 
            return *this ; 
        }
    
 
    Point& Point::operator += (const Point& ObjPoint)  
        {
                x += ObjPoint.x;
                y += ObjPoint.y;
 
                return *this;
        }
 
    Point& Point::operator -= (const Point& ObjPoint)
        {
                x -= ObjPoint.x;
                y -= ObjPoint.y;
 
                return *this;
        }
 
 
    //----------- Implementation of GLOBAL Ostream << Operator  -----------//
    std::ostream& operator << (std::ostream& out,const Point & ObjPoint)
            {
                return out << "[" << ObjPoint.x << "," << ObjPoint.y << "]" ; 
                
            }


Shape_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
47
//
//                                                  (---.Shape_cpp---)
//
#include <iostream>
#include "Shape.hpp"
 
 
    int shape_ctor_calls_counter            = 1 ; 
    int shape_destructor_calls_counter      = 1;
        //----------- Implementation of Constructors -----------//
    Shape::Shape() : id(std::rand())
            {
        //      std::cout << "\n Shape Ctor was called: "<< shape_ctor_calls_counter++ << " times\n" ; 
            }
 
    Shape::~Shape () 
            {
        std::cout   << "\n Shape destructor was called " 
                    << shape_destructor_calls_counter++ << " times"
                    <<" " ; 
            }
        //----------- Implementation of Accessor(s) member functions -----------//
    int Shape::ID()
            {
            
            return id;
            }
    
        std::string Shape::ToString() const
            {
                std::ostringstream os;                   
                os  <<  "id:" << id;                    
                return os.str();                         
            }
 
    
    Shape::Shape(const Shape &ObjShape)
            {
                id = ObjShape.id;
            }
        
 
        //----------- Implementation of GLOBAL(friend) Ostream << Operator  -----------//
        std::ostream& operator << (std::ostream& out,const Shape & ObjShape)
                    {
                        return out << "ID [" << ObjShape.id << "]";
                    }


main
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
#include <iostream>
#include "Line.hpp"
#include "Point.hpp"
#include "Shape.hpp"
#include "Circle.hpp"
#include "boost/shared_ptr.hpp"
#include "Array.cpp"
using namespace std;
 
 
 
int main()
{
        {
 
                    
 
    const unsigned int size_of_data_array = 10; 
 
    double data_x[size_of_data_array] =
                    {1830 , 190.1 , 1914 , 1900 , 1839  , 
                     1865 , 1914  , 1633 , 1656 , 18.95 } ; 
 
    double data_y[size_of_data_array] =
                  { 1903 , 1834 , 1812 , 1088 , 1789, 
                   19.47 , 1211 , 1969 , 1535 , 1628   } ; 
    
            // Typedef for a shared pointer to shape and
            // a typedef for an array with shapes stored as shared pointers.
            typedef boost::shared_ptr<Shape> SmartPointerForShapeClass;
            typedef Array<SmartPointerForShapeClass> SmartShapeArray;
 
            //create an array of smart pointers of shape type of size 8
            const unsigned int array_size = 9 ;
            SmartShapeArray MySmartShapeArray(array_size); //THIS ONE FAILS
 
SmartPointerForShapeClass Point1 (new  Point (data_x[8], data_y[2]));   
SmartPointerForShapeClass Line1   (new  Line  (Point( data_x[1],data_y[2]),Point( data_x[3],data_y[4])));          
SmartPointerForShapeClass Circle1 (new  Circle(Point( data_x[3],data_y[4]),Point( data_x[1],data_y[4])));
 
SmartPointerForShapeClass Point2  (new  Point (data_x[9], data_y[2]));  
SmartPointerForShapeClass Line2   (new  Line  (Point( data_x[1],data_y[3]),Point( data_x[5],data_y[4])));          
SmartPointerForShapeClass Circle2 (new  Circle(Point( data_x[9],data_y[2]),Point( data_x[6],data_y[4])));   
 
SmartPointerForShapeClass Point3  (new  Point (data_x[5], data_y[2]));  
SmartPointerForShapeClass Line3   (new  Line  (Point( data_x[5],data_y[8]),Point( data_x[7],data_y[4])));          
SmartPointerForShapeClass Circle3 (new  Circle(Point( data_x[4],data_y[4]),Point( data_x[3],data_y[8])));   
            
 
    std::cout << "\n\n *Let's SET to " <<" MySmartShapeArray "; 
            
            MySmartShapeArray[0] = Point1;
            MySmartShapeArray[1] = Line1;
            MySmartShapeArray[2] = Circle1;
 
            MySmartShapeArray[3] = Point2;
            MySmartShapeArray[4] = Line2;
            MySmartShapeArray[5] = Circle2;
 
            MySmartShapeArray[6] = Point3;
            MySmartShapeArray[7] = Line3;
            MySmartShapeArray[8] = Circle3;
                
 
            std::cout << "\n\n *Let's Print elements of " <<" MySmartShapeArray "; 
            std::cout << "\n"; 
 
            try 
            {
            for(unsigned int i=0; i<array_size; i++)                    
                {
                    cout << " \n";
                    MySmartShapeArray[i]->Print();
                    cout << " \n";
                }
            }
            catch (ArrayException& objError )
                {
                    cout    << "\n ERROR : Smart Pointers Array is out of bound " 
                            << objError.GetMessage(); 
                }
 
        }
 
        cout    << "\n\n As you can see by using <Smart Pointers>"
                << "\n all nessesary destractors was called automatically"
                << " "
                << endl;
 
        cout    << "\n\n\n\n\n\n\t"; 
    return 0 ; 
}


Ребят помогите пожалуйста разобраться в следующих вопросах.
1. Почему в консоле в самом начале 12 раз вызывается Point destructor and Shape Destructor тоже 12 раз ???
2. По заданию надо показать что мол если мы узаем Smart Point boost то типа все удаляется автоматически
Но ведь если оставить имплементацию Array destructor пустой ну или просто с сообщением то нифига не удаляется только вот в начале выводется вот эти 24 дестрактора
3. В чем вообще тогда соль этого смарт пойтера ????
Мож я тупо что то опять не как нахимичил посмотрите плиз
4. и еще как в цикле сделать присвоение объектов в арей в мейне я имею ввиду (чтоб не писать Поит 1 , поинте 2 и тд ) ??? что то компелятор на меня ругается когда пробую через Класс** объектКласса = нью Класс* (размер) сделать... Тут чо какие то особенности есть при юзание смарт поинтеров
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
09.08.2012, 13:21
Ответы с готовыми решениями:

Помогите разобраться с boost::shared_ptr
shared_prt хранит указатель на динамически создаваемый объект и гарантирует, что объект будет удален только после того как перестанет...

Отличие std::auto_ptr<SomeType> от boost::shared_ptr<SomType>
Господа программисты, хочу задать вам вопрос: чем умный указатель std::auto_ptr&lt;SomeType&gt; отличается от бустового умного указателя...

Qt smart pointers vs std smart pointers
В каких случаях лучше использовать Q*Pointer, а в каких std::*_ptr, или с наследниками QObject лучше всегда использовать средства Qt?

3
2393 / 1920 / 763
Регистрация: 27.07.2012
Сообщений: 5,560
09.08.2012, 13:28
Цитата Сообщение от Leeto Посмотреть сообщение
1. Почему в консоле в самом начале 12 раз вызывается Point destructor and Shape Destructor тоже 12 раз ???
C++
1
2
3
4
5
6
7
8
9
10
11
SmartPointerForShapeClass Point1 (new  Point (data_x[8], data_y[2]));   
SmartPointerForShapeClass Line1   (new  Line  (Point( data_x[1],data_y[2]),Point( data_x[3],data_y[4])));          
SmartPointerForShapeClass Circle1 (new  Circle(Point( data_x[3],data_y[4]),Point( data_x[1],data_y[4])));
 
SmartPointerForShapeClass Point2  (new  Point (data_x[9], data_y[2]));  
SmartPointerForShapeClass Line2   (new  Line  (Point( data_x[1],data_y[3]),Point( data_x[5],data_y[4])));          
SmartPointerForShapeClass Circle2 (new  Circle(Point( data_x[9],data_y[2]),Point( data_x[6],data_y[4])));   
 
SmartPointerForShapeClass Point3  (new  Point (data_x[5], data_y[2]));  
SmartPointerForShapeClass Line3   (new  Line  (Point( data_x[5],data_y[8]),Point( data_x[7],data_y[4])));          
SmartPointerForShapeClass Circle3 (new  Circle(Point( data_x[4],data_y[4]),Point( data_x[3],data_y[8])));
Вот в этом участке кода в конструкторы Line и Circle передаются безымянные объекты типа Point. По завершении работы конструкторов эти объекты разрушаются и соответственно вызываются их деструкторы. Тут у вас ровно 12 штук Point'ов создаётся. Всё по честному.
1
Каратель
Эксперт С++
6610 / 4029 / 401
Регистрация: 26.03.2010
Сообщений: 9,273
Записей в блоге: 1
09.08.2012, 13:30
Цитата Сообщение от Leeto Посмотреть сообщение
В чем вообще тогда соль этого смарт пойтера ????
соль в том что не нужно явно вызывать delete для указателя который он содержит, это сделает деструктор смарт-поинтера

Цитата Сообщение от Leeto Посмотреть сообщение
2. По заданию надо показать что мол если мы узаем Smart Point boost то типа все удаляется автоматически
Но ведь если оставить имплементацию Array destructor пустой ну или просто с сообщением то нифига не удаляется только вот в начале выводется вот эти 24 дестрактора
не путай праведное с грешным, смарт-поинтер отвечает лишь за указатель который он содержит, а твой Array содержит смарт-поинтеры, деструкторы для которых будут вызваны лишь когда ты вызовешь delete[] в Array
1
 Аватар для Leeto
7 / 7 / 3
Регистрация: 23.12.2011
Сообщений: 372
Записей в блоге: 1
09.08.2012, 20:49  [ТС]
Цитата Сообщение от Jupiter Посмотреть сообщение
соль в том что не нужно явно вызывать delete для указателя который он содержит, это сделает деструктор смарт-поинтера


не путай праведное с грешным, смарт-поинтер отвечает лишь за указатель который он содержит, а твой Array содержит смарт-поинтеры, деструкторы для которых будут вызваны лишь когда ты вызовешь delete[] в Array


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

Array_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//                                                      
//                                                  (---.Array_hpp---)
//
#ifndef Array_HPP   // Preprocessor gates
#define Array_HPP
 
    #include <sstream>
    #include <iostream>
    #include <string>       // need also for ArrayException.hpp
    #include "ArrayException.hpp"
 
    template <class T>  //Remove the "=double" default parameter.
    class Array
        {
    
            protected:              // Declaration of private data members 
             unsigned int m_size;
             
              T*           m_data;          //m_data should be a pointer, since you want to allocate data to it
 
            public:                 // Public declaration of data members (in given example haven't ) and member functions 
                static int m_size_default;
                unsigned int array_stack_index; 
                //----------- Declaration of Constructors -----------//
              Array();                                  // Default constructor
              Array(const unsigned int new_size);       // Constructor 
              Array( Array<T>& ObjArray);           // Copy constructor
              ~Array();                                 // Destructor
 
               //----------- Declaration of Modificator(s) member functions -----------//
              void SetElement(const T& ObjType,const  unsigned int index);
              static void DefaultSize( int newSize) ;
 
              //----------- Declaration of  Accessors member functions -----------//
              T& GetElement(const unsigned int index) ;
              static int  DefaultSize() ;
              unsigned int Size() const;
              unsigned int ArrayCurrentIndex();
              
 
              //----------- Declaration of Operators Overloading the class's members -----------//
              Array<T>& operator    =   (const Array& ObjArray);                //Const correctness here.
              const T& operator  [] (unsigned int index) const;
              T& operator       []  (unsigned int index);           
        };
 
    #ifndef Array_cpp // Must be the same name as in source file #define
 
        #include "Array.cpp"
 
    #endif //#ifndef Array_cpp is CLOSED
 
#endif //  #ifndef Array_HPP is CLOSED


ArrayException_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//                                                      
//                                                  (---.ArrayException_hpp---)
//
#ifndef ArrayException_HPP  // Preprocessor gates
#define ArrayException_HPP
 
    
 
 
 
    class ArrayException 
    {
    protected: 
 
    public : 
        ArrayException () {};
        virtual std::string GetMessage() const = 0;
    };  
 
    class OutOfBoundsException : public ArrayException
    {
    private : 
             int m_index;
    public : 
        OutOfBoundsException();
        OutOfBoundsException( int  current_index) : m_index( current_index) 
        {
        
        } 
        std::string GetMessage() const
        
        {
            
            
             
        std::ostringstream os;                          // std::stringstream object
                    os  << "\nEXCEPTION HANDLING ERROR: "
                        << "the given element " 
                        << "with index : " 
                        << m_index 
                        << " is out of bounds\n "   ;
                    return os.str();    
        }
 
    };
 
#endif // ArrayException_HPP


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
31
32
33
34
35
36
37
38
39
40
41
42
// Point.hpp
//
// Header file for Points in two dimensions. A given Point has 3 coordinates
// for compatibility with other systems. However, it is not possible to
// influence the third coordinate and furthermore, the delivered functionality
// is typically two-dimensional.
//
// (C) Copyright Datasim BV 1995 - 2005
 
#ifndef Point_HPP
#define Point_HPP
 
#include <iostream>
using namespace std;
 
 
 
class Point
{
private:
    double x;   // X coordinate
    double y;   // Y coordinate
 
public:
    // Constructors
    Point();                                // Default constructor
    Point(double xval, double yval);        // Initialize with x and y value
    
    ~Point();
 
    // Accessing functions
    double X() const ;                  // The x-coordinate
    void X(double newX);
    double Y() const;                   // The y-coordinate
    void Y(double newY);
 
    friend ostream& operator << (ostream& os, const Point& pt);
};
 
 
 
#endif // Point_HPP


Stack_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    //                                                      
    //                                                  (---.Stack_hpp---)
    //  
    #ifndef STACK_HPP   // Preprocessor gates
    #define STACK_HPP
 
        #include    "Array.hpp"
 
        template<class T>
        class Stack
            {
                private:
 
                    unsigned int m_current;
 
                public:
                
                    Array<T>* m_array; // in assignment only m_current private data member  
    
                    //----------- Declaration of Constructors -----------//
                
                    Stack();                            // Default (Nullary ) Construcotr
                    Stack(int size);                    // Non-nullary Constructor 
                    ~Stack();                           // Destructor
    
                    //----------- Declaration of  Accessors member functions -----------//
                
                    int StackCurrentIndex() const;
                    //----------- Declaration of Setter(s) and Getter(s) member functions -----------//
                    void Push(const T& element) const;          // Add a new element to the array
                    T Pop() const;                              // Remove the last element of the array
                
                    //----------- Declaration of Operators Overloading the class's members -----------//
                    Stack<T>& operator = (const Stack<T>& ObjStack);        //assignment operator
                
            };
 
        #ifndef STACK_CPP 
 
            #include"Stack.cpp"
 
        #endif // STACK_CPP is CLOSED
 
    #endif // // STACK_HPP is CLOSED


Array_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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//                                                      
//                                                  (---.Array_CPP---)
//  
    #ifndef Array_CPP   // Preprocessor gates
    #define Array_CPP
 
        #include "Array.hpp"
        
 
        template <class T>
        int Array<T>::m_size_default = 10;
 
                    //----------- Implementation of Constructors -----------//
        template <class T>
        Array<T>::Array() :  m_size(m_size_default), m_data(new T[m_size]), array_stack_index(0)                                    
            {
            //  std::cout << "Array Default Constructor was called " ;
            }
 
        template <class T>
        Array<T>::Array(const unsigned int new_size) : m_size(new_size), m_data(new T[new_size]), array_stack_index(0)        
            {    //specified by the size input argument                 
            //  std::cout << "Array Constructor was called "; 
            }
 
        template <class T>
        Array<T>::Array( Array& ObjArray)
            {
                 // std::cout << "Array copy Constructor "; 
                m_size    =    ObjArray.m_size;         // shallow copy - this is not dynamic alloc
                array_stack_index = ObjArray.array_stack_index;
                if (ObjArray.m_data)                    // if not zeros then there is a ref. - Deep copy needed
                    {
                        m_data = new T[ObjArray.m_size];
                        for (unsigned int i = 0; i <   ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];
                    }
                else
                m_data = 0;                             //NULL
            }
 
        template <class T>
        Array<T>::~Array()
            {
                std::cout << "Array Destructor was called\n" ;
                delete [] m_data;
            }
 
        //----------- Implementaion of Modificator(s) member(s) function -----------//
        template <class T> 
        void Array<T>::SetElement(const T& ObjType,const unsigned int index)
            {
                array_stack_index = index; 
                    std::cout << "Set Element[" << index << "]<-  "; 
                    if (array_stack_index >= m_size || array_stack_index < 0 )
                        {   
                            std::cout << " Data wasn't setted"; 
                            throw OutOfBoundsException(array_stack_index--);
                        }
                    std::cout << ObjType << "\n"; 
                    m_data[array_stack_index] = ObjType;
            }
 
        template <typename T>
        void Array<T>::DefaultSize( int newSize) 
            { 
                m_size_default = newSize; 
            }
 
        //----------- Implementation of Accessor(s) member functions -----------//
        template <class T> 
        T& Array<T>::GetElement(const unsigned int index) 
            {
                array_stack_index = index; 
                //std::cout << "GetElement[" << index <<"] ->" ;
                    if (array_stack_index >= m_size || array_stack_index < 0)
                        {       
                            std::cout << " Data wasn't getted"; 
                            throw OutOfBoundsException(array_stack_index++);
                        }
 
                return m_data[array_stack_index];
            }
 
        template <typename T>
        int Array<T>::DefaultSize() 
            { 
                return m_size_default;
            }
 
        template<class T>
        unsigned int Array<T>::Size() const
        {
            
            return this->m_size; 
        }
 
        template<class T>
        unsigned int  Array<T>::ArrayCurrentIndex()
            {
                return this->array_stack_index; 
            }
 
        //----------- Implementation of Operators Overloading the class's member -----------//
 
        template <class T>
        Array<T>& Array<T>::operator = (const Array& ObjArray)
            {
             // std::cout << " Array Assignment operator\n";
            if (this == &ObjArray)
                {
                    //std::cout << "Same Array \n"; 
                    return *this;
                }
 
            delete [] m_data;
            // std::cout << "Deleted m_data array\n";
 
            m_size = ObjArray.m_size;       // shallow copy - this is not dynamic alloc
 
            if (ObjArray.m_data)            // if not zeros then there is a ref.
                    {
                        // std::cout <<"im here\n"; 
 
                        m_data = new T[ObjArray.m_size];        // create a new pointee.
 
                        for (unsigned int i = 0; i <    ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];   //copy the points from/to array
                    }
            else
                m_data = 0;  //NULL
 
            return *this;
            }
 
        template <class T> 
        T& Array<T>::operator [] (unsigned int index) 
            {
                //std::cout << "Array [] operator" << std::endl;
                array_stack_index = index; 
                if (array_stack_index >= this->m_size)
                        { 
                            throw OutOfBoundsException(index);
                        }
                return m_data[index];
            }
 
        template <class T> 
        const T& Array<T>::operator [] (unsigned int index) const
        {   
            array_stack_index = index; 
            //std::cout << "const Array [] operator" << std::endl;
            if (array_stack_index > this-> m_size)
                        { 
                            throw OutOfBoundsException(array_stack_index);
                        }
            return m_data[array_stack_index];
        }
 
    #endif //Array_CPP


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
47
48
49
50
51
52
53
54
55
56
57
// Point.cpp
//
// Header file for Points in two dimensions. A given Point has 3 coordinates
// for compatibility with other systems. However, it is not possible to
// influence the third coordinate and furthermore, the delivered functionality
// is typically two-dimensional.
//
 
 
#include "Point.hpp"
#include <cmath>
 
Point::Point() : x(0), y(0) // Colon syntax!!!!!!!!!!!!!!!!!
{// Default constructor
    
//  x = y =0.0;
}
 
Point::Point(double newx, double newy) : x(newx), y(newy)
{// Initialize using newx and newy
    
/*  x = newx;
    y = newy;*/
}
Point::~Point()
{// Des...
    
    cout << "bye my point..\n";
}
 
double Point::X() const
{
    return x;
}
 
void Point::X(double newX)
{ 
    x = newX;
}
 
 
double Point::Y() const 
{
    return y;
}
 
void Point::Y(double newY)
{ 
    y = newY;
}
 
ostream& operator << (ostream& os, const Point& pt)
{
 
    os << "(" << pt.x << "," << pt.y << ")";
    return os;
}


Stack_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//                                                      
//                                                  (---.Stack_cpp---)
//  
#ifndef STACK_CPP // Preprocessor gates
#define STACK_CPP
 
    #include "Stack.hpp"
 
 
    //----------- Implementation of Constructors -----------//
    template<class T>                           
    Stack<T>::Stack()                   // Default constructor
        :m_array(new Array<T>()),m_current(m_array->ArrayCurrentIndex()) 
        {   //the current position is the last index of the Array
            
        }
 
    template<class T>
    Stack<T>::Stack(int size)                   
        :m_array(new Array<T>(size)),m_current(m_array->ArrayCurrentIndex())       
        {   //the current position is the last index of the Array
 
        }
 
    template<class T>
    Stack<T>::~Stack()                                      // Destructor
        {
    //       delete m_array;        
        }
    
    //----------- Implementation of Accessor(s) member functions -----------//
    template<class T>
    int Stack<T>::StackCurrentIndex() const
        {
 
            return m_array->ArrayCurrentIndex();
        }
 
    //----------- Implementaion of Modificator(s) member(s) function -----------//
    
    template<class T>
    void Stack<T>::Push(const T& element) const
        {   
            m_array->SetElement(element,m_array->ArrayCurrentIndex()); 
            m_array->array_stack_index++;   
        }
 
    template<class T>
    T Stack<T>::Pop() const
        {   
            T result = m_array->GetElement(m_array->ArrayCurrentIndex()); 
            m_array->array_stack_index--;
            return result; 
        }
 
    //----------- Implementation of Operators Overloading the class's member -----------//
    template<class T>
    Stack<T>& Stack<T>::operator=(const Stack<T>& ObjStack) // Asignment operator
        {
            if(this!=&ObjStack)        //handle self assignment
            {
                this->Stack<T>::operator=(ObjStack);
                m_current = s.m_current;
            }
 
            return(*this);
        }
#endif


TestSharedPtr_main_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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// TestSharedPtr_main_cpp
//
 
 
#include <vector>
#include "boost/shared_ptr.hpp"
#include "Point.hpp"
#include "Array.hpp"
#include "Stack.hpp"
 
 
// These classes are an upgrade from raw pointers to shared pointers
 
 
///
class Base
{ // Class with non-virtual destructor
private:
    
public:
    Base() { }
    virtual ~Base() { cout << "Base destructor\n\n"; }
    virtual void print() const = 0;
};
 
class Derived : public Base
{ // Derived class
private:
        
public:
    Derived() : Base() { }
    ~Derived() { cout << "Derived destructor\n"; }
    void print() const { cout << "I'm here  derived object\n";}
};
 
// Simple creator (FACTORY) function
boost::shared_ptr<Base> createBase()
{
 
    // In later versions return other derived types
    boost::shared_ptr<Base> result(new Derived());
 
    return result;
}
 
 
void doIt()
{
    /*
    cout << "\n\n Use in Stack-Array containers \n " ;
    typedef Stack<boost::shared_ptr<Base> > ContainerType;
    //typedef ContainerType::iterator iterator;
 
    cout << "\n\n Create a Stack of objects\n " ;
 
    const int N = 4;
    ContainerType con(N);
    try 
    {
        for (int j = 0; j < N; ++j)
        {
            cout << "index " << j << "\n";
            con.Push( createBase());
        }
    }
    catch (ArrayException & Err)
        {
            cout << "something wrong " << Err.GetMessage(); 
        }
    cout << "\n Now iterate and print\n" ;
 
    //iterator myIter;
    for (int j = 0; j < N; ++j)
    {
 
        con.Pop(); 
    }
    */
 
    cout << "\n\n Use in Stack-Array containers \n " ;
    typedef Array<boost::shared_ptr<Base> > ContainerType;
    //typedef ContainerType::iterator iterator;
 
    cout << "\n\n Create a Stack of objects\n " ;
 
    const int N = 4;
    ContainerType con(N);
    try 
    {
        for (int j = 0; j < N; ++j)
        {
            cout << "index " << j << "\n";
            con.SetElement( createBase(),j);
        }
    }
    catch (ArrayException & Err)
        {
            cout << "something wrong " << Err.GetMessage(); 
        }
    cout << "\n Now iterate and print\n" ;
 
    //iterator myIter;
    for (int j = 0; j < N; ++j)
    {
 
        con.GetElement(j)->print(); 
    }
 
 
 
}
 
int main()
{
    doIt();
 
    return 0;
}


Короче проект работает нормально. Но если меняю Array на Stack (см комменты Push() and Pop() аналогия SetElement() and GetElement() ) то проек валится на строчке
cout << "\n\n Create a Stack of objects\n " ; (всмысле дальше этой строчки не идет )
Связь между Array and Stock -> composition

подскажите плиз в чем косяк
Мои подозрения что в
где тут :m_array(new Array<T>()) если да то как исправить подскажите плиз
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
template<class T>                           
    Stack<T>::Stack()                   // Default constructor
        :m_array(new Array<T>()),m_current(m_array->ArrayCurrentIndex()) 
        {   //the current position is the last index of the Array
            
        }
 
    template<class T>
    Stack<T>::Stack(int size)                   
        :m_array(new Array<T>(size)),m_current(m_array->ArrayCurrentIndex())       
        {   //the current position is the last index of the Array
 
        }
Добавлено через 6 часов 7 минут
Цитата Сообщение от Leeto Посмотреть сообщение
Вот допустим другой проект
Сразу хочу сказать Stack скопировал с проекта который работает нормально... т.е. скорее всего ошибка в конструкторе стока

Array_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//                                                      
//                                                  (---.Array_hpp---)
//
#ifndef Array_HPP   // Preprocessor gates
#define Array_HPP
 
    #include <sstream>
    #include <iostream>
    #include <string>       // need also for ArrayException.hpp
    #include "ArrayException.hpp"
 
    template <class T>  //Remove the "=double" default parameter.
    class Array
        {
    
            protected:              // Declaration of private data members 
             unsigned int m_size;
             
              T*           m_data;          //m_data should be a pointer, since you want to allocate data to it
 
            public:                 // Public declaration of data members (in given example haven't ) and member functions 
                static int m_size_default;
                unsigned int array_stack_index; 
                //----------- Declaration of Constructors -----------//
              Array();                                  // Default constructor
              Array(const unsigned int new_size);       // Constructor 
              Array( Array<T>& ObjArray);           // Copy constructor
              ~Array();                                 // Destructor
 
               //----------- Declaration of Modificator(s) member functions -----------//
              void SetElement(const T& ObjType,const  unsigned int index);
              static void DefaultSize( int newSize) ;
 
              //----------- Declaration of  Accessors member functions -----------//
              T& GetElement(const unsigned int index) ;
              static int  DefaultSize() ;
              unsigned int Size() const;
              unsigned int ArrayCurrentIndex();
              
 
              //----------- Declaration of Operators Overloading the class's members -----------//
              Array<T>& operator    =   (const Array& ObjArray);                //Const correctness here.
              const T& operator  [] (unsigned int index) const;
              T& operator       []  (unsigned int index);           
        };
 
    #ifndef Array_cpp // Must be the same name as in source file #define
 
        #include "Array.cpp"
 
    #endif //#ifndef Array_cpp is CLOSED
 
#endif //  #ifndef Array_HPP is CLOSED


ArrayException_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//                                                      
//                                                  (---.ArrayException_hpp---)
//
#ifndef ArrayException_HPP  // Preprocessor gates
#define ArrayException_HPP
 
    
 
 
 
    class ArrayException 
    {
    protected: 
 
    public : 
        ArrayException () {};
        virtual std::string GetMessage() const = 0;
    };  
 
    class OutOfBoundsException : public ArrayException
    {
    private : 
             int m_index;
    public : 
        OutOfBoundsException();
        OutOfBoundsException( int  current_index) : m_index( current_index) 
        {
        
        } 
        std::string GetMessage() const
        
        {
            
            
             
        std::ostringstream os;                          // std::stringstream object
                    os  << "\nEXCEPTION HANDLING ERROR: "
                        << "the given element " 
                        << "with index : " 
                        << m_index 
                        << " is out of bounds\n "   ;
                    return os.str();    
        }
 
    };
 
#endif // ArrayException_HPP


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
31
32
33
34
35
36
37
38
39
40
41
42
// Point.hpp
//
// Header file for Points in two dimensions. A given Point has 3 coordinates
// for compatibility with other systems. However, it is not possible to
// influence the third coordinate and furthermore, the delivered functionality
// is typically two-dimensional.
//
// (C) Copyright Datasim BV 1995 - 2005
 
#ifndef Point_HPP
#define Point_HPP
 
#include <iostream>
using namespace std;
 
 
 
class Point
{
private:
    double x;   // X coordinate
    double y;   // Y coordinate
 
public:
    // Constructors
    Point();                                // Default constructor
    Point(double xval, double yval);        // Initialize with x and y value
    
    ~Point();
 
    // Accessing functions
    double X() const ;                  // The x-coordinate
    void X(double newX);
    double Y() const;                   // The y-coordinate
    void Y(double newY);
 
    friend ostream& operator << (ostream& os, const Point& pt);
};
 
 
 
#endif // Point_HPP


Stack_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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    //                                                      
    //                                                  (---.Stack_hpp---)
    //  
    #ifndef STACK_HPP   // Preprocessor gates
    #define STACK_HPP
 
        #include    "Array.hpp"
 
        template<class T>
        class Stack
            {
                private:
 
                    unsigned int m_current;
 
                public:
                
                    Array<T>* m_array; // in assignment only m_current private data member  
    
                    //----------- Declaration of Constructors -----------//
                
                    Stack();                            // Default (Nullary ) Construcotr
                    Stack(int size);                    // Non-nullary Constructor 
                    ~Stack();                           // Destructor
    
                    //----------- Declaration of  Accessors member functions -----------//
                
                    int StackCurrentIndex() const;
                    //----------- Declaration of Setter(s) and Getter(s) member functions -----------//
                    void Push(const T& element) const;          // Add a new element to the array
                    T Pop() const;                              // Remove the last element of the array
                
                    //----------- Declaration of Operators Overloading the class's members -----------//
                    Stack<T>& operator = (const Stack<T>& ObjStack);        //assignment operator
                
            };
 
        #ifndef STACK_CPP 
 
            #include"Stack.cpp"
 
        #endif // STACK_CPP is CLOSED
 
    #endif // // STACK_HPP is CLOSED


Array_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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
//                                                      
//                                                  (---.Array_CPP---)
//  
    #ifndef Array_CPP   // Preprocessor gates
    #define Array_CPP
 
        #include "Array.hpp"
        
 
        template <class T>
        int Array<T>::m_size_default = 10;
 
                    //----------- Implementation of Constructors -----------//
        template <class T>
        Array<T>::Array() :  m_size(m_size_default), m_data(new T[m_size]), array_stack_index(0)                                    
            {
            //  std::cout << "Array Default Constructor was called " ;
            }
 
        template <class T>
        Array<T>::Array(const unsigned int new_size) : m_size(new_size), m_data(new T[new_size]), array_stack_index(0)        
            {    //specified by the size input argument                 
            //  std::cout << "Array Constructor was called "; 
            }
 
        template <class T>
        Array<T>::Array( Array& ObjArray)
            {
                 // std::cout << "Array copy Constructor "; 
                m_size    =    ObjArray.m_size;         // shallow copy - this is not dynamic alloc
                array_stack_index = ObjArray.array_stack_index;
                if (ObjArray.m_data)                    // if not zeros then there is a ref. - Deep copy needed
                    {
                        m_data = new T[ObjArray.m_size];
                        for (unsigned int i = 0; i <   ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];
                    }
                else
                m_data = 0;                             //NULL
            }
 
        template <class T>
        Array<T>::~Array()
            {
                std::cout << "Array Destructor was called\n" ;
                delete [] m_data;
            }
 
        //----------- Implementaion of Modificator(s) member(s) function -----------//
        template <class T> 
        void Array<T>::SetElement(const T& ObjType,const unsigned int index)
            {
                array_stack_index = index; 
                    std::cout << "Set Element[" << index << "]<-  "; 
                    if (array_stack_index >= m_size || array_stack_index < 0 )
                        {   
                            std::cout << " Data wasn't setted"; 
                            throw OutOfBoundsException(array_stack_index--);
                        }
                    std::cout << ObjType << "\n"; 
                    m_data[array_stack_index] = ObjType;
            }
 
        template <typename T>
        void Array<T>::DefaultSize( int newSize) 
            { 
                m_size_default = newSize; 
            }
 
        //----------- Implementation of Accessor(s) member functions -----------//
        template <class T> 
        T& Array<T>::GetElement(const unsigned int index) 
            {
                array_stack_index = index; 
                //std::cout << "GetElement[" << index <<"] ->" ;
                    if (array_stack_index >= m_size || array_stack_index < 0)
                        {       
                            std::cout << " Data wasn't getted"; 
                            throw OutOfBoundsException(array_stack_index++);
                        }
 
                return m_data[array_stack_index];
            }
 
        template <typename T>
        int Array<T>::DefaultSize() 
            { 
                return m_size_default;
            }
 
        template<class T>
        unsigned int Array<T>::Size() const
        {
            
            return this->m_size; 
        }
 
        template<class T>
        unsigned int  Array<T>::ArrayCurrentIndex()
            {
                return this->array_stack_index; 
            }
 
        //----------- Implementation of Operators Overloading the class's member -----------//
 
        template <class T>
        Array<T>& Array<T>::operator = (const Array& ObjArray)
            {
             // std::cout << " Array Assignment operator\n";
            if (this == &ObjArray)
                {
                    //std::cout << "Same Array \n"; 
                    return *this;
                }
 
            delete [] m_data;
            // std::cout << "Deleted m_data array\n";
 
            m_size = ObjArray.m_size;       // shallow copy - this is not dynamic alloc
 
            if (ObjArray.m_data)            // if not zeros then there is a ref.
                    {
                        // std::cout <<"im here\n"; 
 
                        m_data = new T[ObjArray.m_size];        // create a new pointee.
 
                        for (unsigned int i = 0; i <    ObjArray.m_size; i++)
                        m_data[i]    =    ObjArray.m_data[i];   //copy the points from/to array
                    }
            else
                m_data = 0;  //NULL
 
            return *this;
            }
 
        template <class T> 
        T& Array<T>::operator [] (unsigned int index) 
            {
                //std::cout << "Array [] operator" << std::endl;
                array_stack_index = index; 
                if (array_stack_index >= this->m_size)
                        { 
                            throw OutOfBoundsException(index);
                        }
                return m_data[index];
            }
 
        template <class T> 
        const T& Array<T>::operator [] (unsigned int index) const
        {   
            array_stack_index = index; 
            //std::cout << "const Array [] operator" << std::endl;
            if (array_stack_index > this-> m_size)
                        { 
                            throw OutOfBoundsException(array_stack_index);
                        }
            return m_data[array_stack_index];
        }
 
    #endif //Array_CPP


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
47
48
49
50
51
52
53
54
55
56
57
// Point.cpp
//
// Header file for Points in two dimensions. A given Point has 3 coordinates
// for compatibility with other systems. However, it is not possible to
// influence the third coordinate and furthermore, the delivered functionality
// is typically two-dimensional.
//
 
 
#include "Point.hpp"
#include <cmath>
 
Point::Point() : x(0), y(0) // Colon syntax!!!!!!!!!!!!!!!!!
{// Default constructor
    
//  x = y =0.0;
}
 
Point::Point(double newx, double newy) : x(newx), y(newy)
{// Initialize using newx and newy
    
/*  x = newx;
    y = newy;*/
}
Point::~Point()
{// Des...
    
    cout << "bye my point..\n";
}
 
double Point::X() const
{
    return x;
}
 
void Point::X(double newX)
{ 
    x = newX;
}
 
 
double Point::Y() const 
{
    return y;
}
 
void Point::Y(double newY)
{ 
    y = newY;
}
 
ostream& operator << (ostream& os, const Point& pt)
{
 
    os << "(" << pt.x << "," << pt.y << ")";
    return os;
}


Stack_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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//                                                      
//                                                  (---.Stack_cpp---)
//  
#ifndef STACK_CPP // Preprocessor gates
#define STACK_CPP
 
    #include "Stack.hpp"
 
 
    //----------- Implementation of Constructors -----------//
    template<class T>                           
    Stack<T>::Stack()                   // Default constructor
        :m_array(new Array<T>()),m_current(m_array->ArrayCurrentIndex()) 
        {   //the current position is the last index of the Array
            
        }
 
    template<class T>
    Stack<T>::Stack(int size)                   
        :m_array(new Array<T>(size)),m_current(m_array->ArrayCurrentIndex())       
        {   //the current position is the last index of the Array
 
        }
 
    template<class T>
    Stack<T>::~Stack()                                      // Destructor
        {
    //       delete m_array;        
        }
    
    //----------- Implementation of Accessor(s) member functions -----------//
    template<class T>
    int Stack<T>::StackCurrentIndex() const
        {
 
            return m_array->ArrayCurrentIndex();
        }
 
    //----------- Implementaion of Modificator(s) member(s) function -----------//
    
    template<class T>
    void Stack<T>::Push(const T& element) const
        {   
            m_array->SetElement(element,m_array->ArrayCurrentIndex()); 
            m_array->array_stack_index++;   
        }
 
    template<class T>
    T Stack<T>::Pop() const
        {   
            T result = m_array->GetElement(m_array->ArrayCurrentIndex()); 
            m_array->array_stack_index--;
            return result; 
        }
 
    //----------- Implementation of Operators Overloading the class's member -----------//
    template<class T>
    Stack<T>& Stack<T>::operator=(const Stack<T>& ObjStack) // Asignment operator
        {
            if(this!=&ObjStack)        //handle self assignment
            {
                this->Stack<T>::operator=(ObjStack);
                m_current = s.m_current;
            }
 
            return(*this);
        }
#endif


TestSharedPtr_main_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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
// TestSharedPtr_main_cpp
//
 
 
#include <vector>
#include "boost/shared_ptr.hpp"
#include "Point.hpp"
#include "Array.hpp"
#include "Stack.hpp"
 
 
// These classes are an upgrade from raw pointers to shared pointers
 
 
///
class Base
{ // Class with non-virtual destructor
private:
    
public:
    Base() { }
    virtual ~Base() { cout << "Base destructor\n\n"; }
    virtual void print() const = 0;
};
 
class Derived : public Base
{ // Derived class
private:
        
public:
    Derived() : Base() { }
    ~Derived() { cout << "Derived destructor\n"; }
    void print() const { cout << "I'm here  derived object\n";}
};
 
// Simple creator (FACTORY) function
boost::shared_ptr<Base> createBase()
{
 
    // In later versions return other derived types
    boost::shared_ptr<Base> result(new Derived());
 
    return result;
}
 
 
void doIt()
{
    /*
    cout << "\n\n Use in Stack-Array containers \n " ;
    typedef Stack<boost::shared_ptr<Base> > ContainerType;
    //typedef ContainerType::iterator iterator;
 
    cout << "\n\n Create a Stack of objects\n " ;
 
    const int N = 4;
    ContainerType con(N);
    try 
    {
        for (int j = 0; j < N; ++j)
        {
            cout << "index " << j << "\n";
            con.Push( createBase());
        }
    }
    catch (ArrayException & Err)
        {
            cout << "something wrong " << Err.GetMessage(); 
        }
    cout << "\n Now iterate and print\n" ;
 
    //iterator myIter;
    for (int j = 0; j < N; ++j)
    {
 
        con.Pop(); 
    }
    */
 
    cout << "\n\n Use in Stack-Array containers \n " ;
    typedef Array<boost::shared_ptr<Base> > ContainerType;
    //typedef ContainerType::iterator iterator;
 
    cout << "\n\n Create a Stack of objects\n " ;
 
    const int N = 4;
    ContainerType con(N);
    try 
    {
        for (int j = 0; j < N; ++j)
        {
            cout << "index " << j << "\n";
            con.SetElement( createBase(),j);
        }
    }
    catch (ArrayException & Err)
        {
            cout << "something wrong " << Err.GetMessage(); 
        }
    cout << "\n Now iterate and print\n" ;
 
    //iterator myIter;
    for (int j = 0; j < N; ++j)
    {
 
        con.GetElement(j)->print(); 
    }
 
 
 
}
 
int main()
{
    doIt();
 
    return 0;
}


Короче проект работает нормально. Но если меняю Array на Stack (см комменты Push() and Pop() аналогия SetElement() and GetElement() ) то проек валится на строчке
cout << "\n\n Create a Stack of objects\n " ; (всмысле дальше этой строчки не идет )
Связь между Array and Stock -> composition

подскажите плиз в чем косяк
Мои подозрения что в
где тут :m_array(new Array<T>()) если да то как исправить подскажите плиз
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
template<class T>                           
    Stack<T>::Stack()                   // Default constructor
        :m_array(new Array<T>()),m_current(m_array->ArrayCurrentIndex()) 
        {   //the current position is the last index of the Array
            
        }
 
    template<class T>
    Stack<T>::Stack(int size)                   
        :m_array(new Array<T>(size)),m_current(m_array->ArrayCurrentIndex())       
        {   //the current position is the last index of the Array
 
        }
Ребята без вас не как не справляюсь !
Выручайте !
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
09.08.2012, 20:49
Помогаю со студенческими работами здесь

Smart pointers
Уважаемые форумчане, такой вопрос: возможно ли как то в одном контейнере (в векторе например) хранить shared_ptr и указатели на lvalue....

Smart pointers + полиморфизм + делегирование. Ошибка компиляции
Доброго времени суток, уважаемые форумчане! Есть вопрос по поводу использования умных указателей в качестве указателей на абстрактные...

Smart pointers при создании нового окна
Привет. Используются ли стандартные си плюсовые smart pointers при создании окон? unique_ptr&lt;Dialog&gt; dialog;

Smart Pointers: что такое и как с этим работать?
Народ, объясните мне что такое Smart Pointers, зачем нужны и как с ними работать?

Boost начало работы: Undefined reference to `boost::system::generic_category() '
Добрый день Собственно говоря возникла необходимость использовать boost в работе. Поставил так: sudo apt-get install boostlib-all-dev ...


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

Или воспользуйтесь поиском по форуму:
4
Ответ Создать тему
Новые блоги и статьи
SDL3 для Web (WebAssembly): Основы отладки веб-приложений на SDL3 по USB и Wi-Fi, запущенных в браузере мобильных устройств
8Observer8 07.02.2026
Содержание блога Браузер Chrome имеет средства для отладки мобильных веб-приложений по USB. В этой пошаговой инструкции ограничимся работой с консолью. Вывод в консоль - это часть процесса. . .
SDL3 для Web (WebAssembly): Обработчик клика мыши в браузере ПК и касания экрана в браузере на мобильном устройстве
8Observer8 02.02.2026
Содержание блога Для начала пошагово создадим рабочий пример для подготовки к экспериментам в браузере ПК и в браузере мобильного устройства. Потом напишем обработчик клика мыши и обработчик. . .
Философия технологии
iceja 01.02.2026
На мой взгляд у человека в технических проектах остается роль генерального директора. Все остальное нейронки делают уже лучше человека. Они не могут нести предпринимательские риски, не могут. . .
SDL3 для Web (WebAssembly): Вывод текста со шрифтом TTF с помощью SDL3_ttf
8Observer8 01.02.2026
Содержание блога В этой пошаговой инструкции создадим с нуля веб-приложение, которое выводит текст в окне браузера. Запустим на Android на локальном сервере. Загрузим Release на бесплатный. . .
SDL3 для Web (WebAssembly): Сборка C/C++ проекта из консоли
8Observer8 30.01.2026
Содержание блога Если вы откроете примеры для начинающих на официальном репозитории SDL3 в папке: examples, то вы увидите, что все примеры используют следующие четыре обязательные функции, а. . .
SDL3 для Web (WebAssembly): Установка Emscripten SDK (emsdk) и CMake для сборки C и C++ приложений в Wasm
8Observer8 30.01.2026
Содержание блога Для того чтобы скачать Emscripten SDK (emsdk) необходимо сначало скачать и уставить Git: Install for Windows. Следуйте стандартной процедуре установки Git через установщик. . . .
SDL3 для Android: Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 29.01.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами. Версия v3 была полностью переписана на Си, в. . .
Инструменты COM: Сохранение данный из VARIANT в файл и загрузка из файла в VARIANT
bedvit 28.01.2026
Сохранение базовых типов COM и массивов (одномерных или двухмерных) любой вложенности (деревья) в файл, с возможностью выбора алгоритмов сжатия и шифрования. Часть библиотеки BedvitCOM Использованы. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru