Let's say the class contains a link called matrix _:
Class.h
class Class { Matrix& matrix_; }
Class.cpp
Class::Class() : matrix_(Matrix()) { }
I get an error: invalid initialization of a non-constant reference of type "Matrix & from temporary type" Matrix ".
I see that the problem is that the temporary object will disappear and the link will point to NULL. How to create a permanent object for a link? I want to use the link because this member must be permanent.
Class::Class() : matrix_(Matrix()) trying to establish a link to an indication of a temporary object that is illegal.
Class::Class() : matrix_(Matrix())
, const , , .
, :
class Class { const Matrix matrix_; };
:
Class::Class() : matrix_() /* or any params to the constructor if you need them */ { }
.
class Class { Matrix & matrix_; public: Class(Matrix & matrix); }; Class::Class(Matrix & matrix) : matrix_(matrix) { }
, ( ++ ), , const.
, . "" . ( ) . , , , .
class Class { Matrix* const matrix_; }
Class::Class() : matrix_(new Matrix()) { }
You do not need to use the link in order for this member to be permanent. You can use boost::scoped_ptr<const Matrix>.
boost::scoped_ptr<const Matrix>
class Class { public: Class(); private: boost::scoped_ptr<const Matrix> _matrix; } Class::Class() : _matrix(new Matrix) { }
Source: https://habr.com/ru/post/1775000/More articles:MATLAB: printing comparative columns for elements from different vectors - printfprint time with every call to std :: cout - c ++Do I need to call EndInvoke in a callback from EventHandler.BeginInvoke (C # .Net 3.5) - multithreadingXML output XML will lose line breaks - c #Rare case-sensitive applications with Postgres - ruby-on-railsSWFObject / load smil file - javascriptSpring, Morphia implementation and DataAccessException - javaIs there any reason to support the WCF interface in a separate file? - interfaceText field input mask - dateC ++ friend classes - c ++All Articles