Czy to jest najbardziej optymalna metoda czytania prywatnej macierzy z innego obiektu.

0

Dany jest taki problem. Jest obiekt a klasy myclass. Zawiera prywatny matrix z biblioteki boost alokowany dynamicznie. Istnieje obiekt klasy myclass2, który musi przeczytać macierz z obiektu a. Ja rozwiązałem problem w ten sposób:

plik typedef.hpp

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
using namespace boost::numeric::ublas;
//typedef  boost::scoped_ptr<matrix<int> > Mobject;
typedef boost::shared_ptr<matrix<int> > Mobject;
 

plik myclass.hpp

#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>

#include<iostream>
#include <string>

#include <boost/numeric/ublas/matrix.hpp>
#include <boost/scoped_ptr.hpp>
using namespace boost::numeric::ublas;
#include "typedef.hpp"

class myclass
{
	 private:
	  Mobject m;
	 public:
		  myclass();
		  Mobject getMatrix();
};
 

plik myclass.cpp

#include "myclass.hpp"

myclass::myclass()
{
	  m.reset(new matrix<int> (20,20));
	  (*m)(3,7) = 5;
}


Mobject myclass::getMatrix()
{
	 return m;
}
 

plik myclass2.hpp

#include "typedef.hpp"
#include <boost/numeric/ublas/io.hpp>
#include <iostream>
class myclass2
{
	 private:
		  Mobject m;
	 public:
		  myclass2(Mobject );
		  void print();
};
 

plik myclass2.cpp

#include "myclass2.hpp"

myclass2::myclass2(Mobject a)
{
	 m = a;
}

void myclass2::print()
{
	 std::cout<<"m="<<(*m)(3,7)<<std::endl;
	 std::cout<<"m2="<<(*m)(5,6)<<std::endl;
}
 

plik main.cpp

#include "myclass.hpp"
#include "myclass2.hpp"

int main()
{
	 myclass a;
	 myclass2 b(a.getMatrix());
	 b.print();
}
 

Kompiluje się to i działa.
Moje pytanie dotyczy tego czy to jest najbardziej optymalna, elegancka i bezpieczna metoda czytania prywatnej macierzy(obiektu) z innego obiektu?

1
myclass::myclass() : m(new matrix<int>(20, 20))
{
      (*m)(3,7) = 5;
}
  1. Używanie using namespace w plikach nagłówkowych jest generalnie złą praktyką.
  2. Mobject jest kiepską nazwą, bo nic nie mówi. Tak samo myclass.
  3. Strasznie bałaganiarskie include``y, szczególnie myclass.hpp`.
0

Używasz boost::shared_ptr (jest jakiś powód, dlaczego nie chcesz std::shared_ptr?), używaj też boost::make_shared.

Powinieneś zwracać Mobject const&.

Mobject getMatrix();

Do tego wszystko, co @twonek napisał. Nie wiem, czy to przykład (jeśli tak to polecam używanie standardowych foo, bar, baz, quux), czy nie, ale jest to strasznie nieczytelne.

1 użytkowników online, w tym zalogowanych: 0, gości: 1