重载运算符+和-为何出错

YUSHUIHE 2015-09-17 10:15:00
//except.h 文件
#ifndef EXCEPTION_CLASSES
#define EXCEPTION_CLASSES

#include <strstream>
#include <string>

using namespace std;

class baseException
{
public:
baseException(const string& str = ""):
msgString(str)
{
if (msgString == "")
msgString = "Unspecified exception";
}

string what() const
{
return msgString;
}

// protected allows a derived class to access msgString.
// chapter 13 discusses protected in detail
protected:
string msgString;
};

// failure to allocate memory (new() returns NULL)//内存分配错误
class memoryAllocationError: public baseException
{
public:
memoryAllocationError(const string& msg = ""):
baseException(msg)
{}
};

// function argument out of proper range //范围错误
class rangeError: public baseException
{
public:
rangeError(const string& msg = ""):
baseException(msg)
{}
};

// index out of range //索引范围错误
class indexRangeError: public baseException
{
public:
indexRangeError(const string& msg, int i, int size):
baseException()
{
char indexString[80];
ostrstream indexErr(indexString, 80);

indexErr << msg << " index " << i << " size = " << size << ends;
// indexRangeError can modify msgString, since it is in
// the protected section of baseException
msgString = indexString;
}
};

// attempt to erase from an empty container //下溢错误
class underflowError: public baseException
{
public:
underflowError(const string& msg = ""):
baseException(msg)
{}
};

// attempt to insert into a full container //溢出错误
class overflowError: public baseException
{
public:
overflowError(const string& msg = ""):
baseException(msg)
{}
};

// error in expression evaluation //表达式错误
class expressionError: public baseException
{
public:
expressionError(const string& msg = ""):
baseException(msg)
{}
};

// bad object reference //参数错误
class referenceError: public baseException
{
public:
referenceError(const string& msg = ""):
baseException(msg)
{}
};

// feature not implemented //不是执行错误
class notImplementedError: public baseException
{
public:
notImplementedError(const string& msg = ""):
baseException(msg)
{}
};

// date errors //日期错误
class dateError: public baseException
{
public:
dateError(const string& first, int v, const string& last):
baseException()
{
char dateStr[80];
ostrstream dateErr(dateStr, 80);

dateErr << first << ' ' << v << ' ' << last << ends;
// dateError can modify msgString, since it is in
// the protected section of baseException
msgString = dateStr;
}
};

// error in graph class//图错误
class graphError: public baseException
{
public:
graphError(const string& msg = ""):
baseException(msg)
{}
};

// file open error
class fileOpenError: public baseException
{
public:
fileOpenError(const string& fname):
baseException()
{
char errorStr[80];
ostrstream fileErr(errorStr, 80);

fileErr << "Cannot open \"" << fname << "\"" << ends;
// fileOpenError can modify msgString, since it is in
// the protected section of baseException
msgString = errorStr;
}
};

// error in graph class
class fileError: public baseException
{
public:
fileError(const string& msg = ""):
baseException(msg)
{}
};

#endif // EXCEPTION_CLASSES

//矩阵类 头文件d_matrix.h

#ifndef MATRIX_CLASS
#define MATRIX_CLASS

#include <iostream>
#include <vector>

#include "d_except.h"

using namespace std;

template <typename T>
class matrix;
template <typename T>
matrix<T> operator+(const matrix<T>& left,const matrix<T>& right);
template <typename T>
matrix<T> operator-(const matrix<T>& left,const matrix<T>& right);

template <typename T>
class matrix
{
public:
matrix(int numRows = 1, int numCols = 1, const T& initVal = T());
// constructor.
// Postcondition: create array having numRows x numCols elements
// all of whose elements have value initVal

vector<T>& operator[] (int i);
// index operator.
// Precondition: 0 <= i < nRows. a violation of this
// precondition throws the indexRangeError exception.
// Postcondition: if the operator is used on the left-hand
// side of an assignment statement, an element of row i
// is changed

const vector<T>& operator[](int i) const;
// version for constant objects

int rows() const;
// return number of rows
int cols() const;
// return number of columns

void resize(int numRows, int numCols);
// modify the matrix size.
// Postcondition: the matrix has size numRows x numCols.
// any new elements are filled with the default value of type T
friend matrix<T> operator+(const matrix<T>& left,const matrix<T>& right);
friend matrix<T> operator-(const matrix<T>& left,const matrix<T>& right);
private:
int nRows, nCols;
// number of rows and columns

vector<vector<T> > mat;
// matrix is implemented as nRows vectors (rows),
// each having nCols elements (columns)
};

template <typename T>
matrix<T>::matrix(int numRows, int numCols, const T& initVal):
nRows(numRows), nCols(numCols),
mat(numRows, vector<T>(numCols,initVal))
{}

// non-constant version. provides general access to matrix
// elements
template <typename T>
vector<T>& matrix<T>::operator[] (int i)
{
if (i < 0 || i >= nRows)
throw indexRangeError(
"matrix: invalid row index", i, nRows);

return mat[i];
}

// constant version. can be used with a constant object.
// does not allow modification of a matrix element
template <typename T>
const vector<T>& matrix<T>::operator[] (int i) const
{
if (i < 0 || i >= nRows)
throw indexRangeError(
"matrix: invalid row index", i, nRows);

return mat[i];
}

template <typename T>
int matrix<T>::rows() const
{
return nRows;
}

template <typename T>
int matrix<T>::cols() const
{
return nCols;
}

template <typename T>
void matrix<T>::resize(int numRows, int numCols)
{
int i;

// handle case of no size change with a return
if (numRows == nRows && numCols == nCols)
return;

// assign the new matrix size
nRows = numRows;
nCols = numCols;

// resize to nRows rows
mat.resize(nRows);

// resize each row to have nCols columns
for (i=0; i < nRows; i++)
mat[i].resize(nCols);
}

template<typename T>
matrix<T> operator+(const matrix<T>& left,const matrix<T>& right)
{
matrix<T> result;//结果
int i,j;
if(left.nRows()==right.nRows()&&left.cols()==right.cols())
{
for(i=0;i!=left.nRows();i++)
for(j=0;j!=left.cols();j++)
result[i][j]=left[i][j]+right[i][j];
}
return result;
}

template<typename T>
matrix<T> operator-(const matrix<T>& left,const matrix<T>& right)
{
matrix<T> result; //结果
int i,j;
if(left.nRows()==right.nRows()&&left.cols()==right.cols())
{
for(i=0;i!=left.nRows();i++)
for(j=0;j!=left.cols();j++)
result[i][j]=left[i][j]-right[i][j];
}
return result;
}

#endif // MATRIX_CLASS

11-41.cpp文件
#include"d_matrix.h"

int main()
{
matrix<int> A,B,C,D;
int i,j,k=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
A[i][j]=k;//赋值为1-9
k++;
}
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
A[i][j]=i; //赋值为0-2
}
C=A+B;//调用matrix类的重载+运算符
D=A-B;//调用matrix类的重载-运算符
int he=0,cha=0;
for(i=0;i<3;i++)
for(j=0;j<3;j++)
{
he+=C[i][j];
cha+=D[i][j];
}
cout<<"两个矩阵的和="<<he<<" 差="<<cha<<endl;

return 0;
}

编译时出错:1>10-31.obj : error LNK2019: 无法解析的外部符号 "class matrix<int> __cdecl operator-(class matrix<int> const &,class matrix<int> const &)" (??G@YA?AV?$matrix@H@@ABV0@0@Z),该符号在函数 _main 中被引用
1>10-31.obj : error LNK2019: 无法解析的外部符号 "class matrix<int> __cdecl operator+(class matrix<int> const &,class matrix<int> const &)" (??H@YA?AV?$matrix@H@@ABV0@0@Z),该符号在函数 _main 中被引用
1>E:\C++STL\no5\5-10-3135\Debug\5-10-3135.exe : fatal error LNK1120: 2 个无法解析的外部命令
请高师帮忙
...全文
181 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
YUSHUIHE 2015-09-20
  • 打赏
  • 举报
回复
感谢各位的回答,特别是1楼和4楼的老师,错误有三:一是operator+和operator-后未加<> ;二是将rows()写成nRows();三是对临时对象未初始化。 改后,编译和运行都成功了,真是很高兴。
iyomumx 2015-09-18
  • 打赏
  • 举报
回复
参考 C++ FAQ 改成
  friend matrix<T> operator+ <>(const matrix<T>& left,const matrix<T>& right);
  friend matrix<T> operator- <>(const matrix<T>& left,const matrix<T>& right);
CyberLogix 2015-09-18
  • 打赏
  • 举报
回复
重载函数声明为friend,并且left.nRows()==right.nRows()写错了吧应该是left.rows()==right.rows()&&
iyomumx 2015-09-18
  • 打赏
  • 举报
回复
引用 2 楼 YUSHUIHE 的回复:
按1楼的老师说的,改后,编译出错:d_matrix.h(127): error C2064: 项不会计算为接受 0 个参数的函数。10-31.cpp(207): 参见对正在编译的函数 模板 实例化“matrix<T> +<int>(const matrix<T> &,const matrix<T> &)”的引用。 还请高师指教。
那两个operator里写了很多 nRows() 之类的代码,但nRows是个int啊
YUSHUIHE 2015-09-18
  • 打赏
  • 举报
回复
按1楼的老师说的,改后,编译出错:d_matrix.h(127): error C2064: 项不会计算为接受 0 个参数的函数。10-31.cpp(207): 参见对正在编译的函数 模板 实例化“matrix<T> +<int>(const matrix<T> &,const matrix<T> &)”的引用。 还请高师指教。

64,684

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧