【发布时间】:2020-04-09 10:20:32
【问题描述】:
我编写了一个 C++ 程序来检查矩阵是否稀疏。出现的语法错误如下:
main.cpp:56:8: error: deduced class type ‘matrix’ in function return type
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:11:7: note: ‘template class matrix’ declared here
class matrix
^~~~~~
main.cpp:56:8: error: prototype for ‘matrix matrix::add(matrix)’ does not match any in class ‘matrix’
matrix matrix <T>::add(matrix r)
^~~~~~~~~~
main.cpp:19:9: error: candidate is: matrix matrix::add(matrix&)
matrix add(matrix&);
^~~*
程序是:
#include<iostream>
#include <exception>
using namespace std;
class mismatchDimension:public exception
{
public:
void error_Msg () const;
};
template < class T >
class matrix
{
int row;
int col;
T ele[10][10];
public:
void get ();
bool check_Sparse ();
matrix add (matrix &);
void print ();
};
//no changes to be made to the above code
void mismatchDimension::error_Msg () const const //Error printing method
{
cout << "Dimension of matrices do not match" << endl;
}
template < class T >
void matrix < T >::get () //Element input of matrix
{
cin >> row;
cin >> col;
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
cin >> ele[j][i];
}
}
template < class T >
bool matrix < T >::check_Sparse () //Check if the matrix is sparse
{
int i, j, t;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
if (ele[j][i] == 0) ++t;
}
}
if (t > (row * col) / 2) return true;
else return false;
}
template < class T >
matrix matrix < T >::add (matrix r) //Addition of the matrices
{
mismatchDimension z;
int i, j;
matrix < T > w;
if (row != r.row && col != r.col) throw z;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
w.ele[j][i] = ele[j][i] + r.ele[j][i];
}
}
return w;
}
template < class T >
void matrix < T >::print () //printing the matrix
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++) cout << ele[j][i] << endl;
}
}
// no changes to be made below
int
main ()
{
matrix < int >m1, m2, m3;
m1.get ();
m2.get ();
try
{
m3 = m1.add (m2);
m3.print ();
} catch (mismatchDimension & m)
{
m.error_Msg ();
}
if (m1.check_Sparse ())
cout << "Matrix is sparse" << endl;
else
cout << "Matrix is not sparse" << endl;
}
【问题讨论】:
-
void mismatchDimension::error_Msg () const const两次常量? JK,它的matrix matrix < T >::add (matrix r)实现。应该是matrix matrix < T >::add (matrix& r)
标签: c++