你可以使用的一个技巧是让非const的operator()(int,int)方法返回一个小帮助对象。帮助器用于区分分配到矩阵中并仅提取一个值。这可以让你对这两个操作有不同的行为。尤其是,如果有人试图分配一个必须为零的值,则可以抛出。
这段代码至少在VC10中为我编译,但显然没有链接。
template <class T>
class tridiagonal
{
public:
// Helper class that let's us tell when the user is
// assigning into the matrix and when they are just
// getting values.
class helper
{
tridiagonal<T> &m_parent;
int m_i, m_j;
public:
helper(tridiagonal<T> &parent, int i, int j)
: m_parent(parent), m_i(i), m_j(j)
{}
// Converts the helper class to the underlying
// matrix value. This doesn't allow assignment.
operator const T &() const {
// Just call the const operator()
const tridiagonal<T> &constParent = m_parent;
return constParent(m_i, m_j);
}
// Assign a value into the matrix.
// This is only called for assignment.
const T & operator= (const T &newVal) {
// If we are pointing off the diagonal, throw
if (abs(m_i - m_j) > 1) {
throw std::exception("Tried to assign to a const matrix element");
}
return m_parent.assign(m_i, m_j, newVal);
}
};
tridiagonal();
~tridiagonal();
helper operator()(int i, int j)
{
return helper(*this, i,j);
}
const T& operator()(int i, int j) const;
private:
T& assign(int i, int j, const T &newVal);
//holds data of just the diagonals
T * m_upper;
T * m_main;
T * m_lower;
};
int main(int argc, const char * argv[])
{
tridiagonal<double> mat;
std::cout << mat(0,0) << std::endl;
const tridiagonal<double> & constMat = mat;
std::cout << mat(2,3) << std::endl;
// Compiles and works
mat(2,3) = 10.0;
// Compiles, but throws at runtime
mat(1, 5) = 20.0;
// Doesn't compile
// constMat(3,3) = 12.0;
return 0;
}
这已经有一段时间,因为我已经做到了这一点,所以你可能会发现你需要添加更多一点的辅助类,这取决于你如何使用矩阵。
其实通过这个工作是一个很好的C++练习。 :)
我选择在有人尝试修改非对角线元素时抛出。这确实很麻烦,但是分配要求界面保持原样。谢谢您的帮助。 – 2012-04-11 00:06:20