문제

I have two classes, a Matrix, and then a Diagonal Matrix that inherits from the Matrix class.

Obviously, converting from Diagonal to Matrix is easy, but converting back requires a conversion.

class Diagonal : public Matrix<T>
{  
  operator Matrix<T>() const;
};

Exists in my code, which I thought should convert. In main, I have:

  Matrix<float> theMatrix(size,size);
  Diagonal<float> theDiag(size,size);
  theDiag = theMatrix;

Everything runs fine except the conversion, which tells me:

 no known conversion for argument 1 from ‘Matrix<float>’ to ‘const Diagonal<float>&’

Any suggestions? Thanks.

도움이 되었습니까?

해결책

Your code

class Diagonal : public Matrix<T>
{  
  operator Matrix<T>() const;
};

defines a conversion from Diagonal<T> to Matrix<T>, whereas your assignment expects a conversion from Matrix<T> to Diagonal<T>.

Did you mean to write this instead?

class Matrix<T>
{  
  operator Diagonal<T>() const;
};

Now even if this works* (which I doubt, since it will cause a cyclic dependency), I'm not sure if it makes sense from a semantic perspective. Not every matrix is a diagonal matrix, so converting from a matrix into a diagonal matrix cannot preserve all data. Using implicit conversions for this situation is a bad idea from a design perspective.

*An alternative would be to define operator=(const Matrix<T>&) for Diagonal<T>.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top