【发布时间】:2021-08-22 15:55:00
【问题描述】:
我有一个如下所示的类数据集
template <class StorageType> class Dataset
{
private:
class Row
{
private:
uInt32 NCol;
StorageType *Data;
public:
Row(){
Data = NULL;
}
void SetCol(uInt32 Col){
if((Data = new StorageType[Col]) == NULL)
{
cout << "Dataset::memory exhausted ... exiting" << endl;
exit(1);
}
NCol = Col;
}
~Row(){
if(Data != NULL)
{
delete []Data;
}
}
StorageType &operator[](uInt32 Col){
return Data[Col];
}
};
Row *Array;
uInt32 NRow;
uInt32 NCol;
public:
Dataset(uInt32 Row, uInt32 Col)
{
if((Array = new Row[Row]) == NULL){
cerr << "Dataset::memory exhausted ... exiting" << endl;
exit(1);
}
register uInt32 i;
for(i = 0;i < Row;i++)
{
Array[i].SetCol(Col);
}
NRow = Row;
NCol = Col;
}
Dataset(Dataset<StorageType> &B)
{
NRow = B.GetNoOfRows();
NCol = B.GetNoOfCols();
if((Array = new Row[NRow]) == NULL){
cerr << "Martix::memory exhausted ... exiting" << endl;
exit(1);
}
register uInt32 i,j;
for(i = 0;i < NRow;i++)
{
Array[i].SetCol(NCol);
for(j = 0;j < NCol;j++)
{
Array[i][j] = B[i][j];
}
}
}
virtual ~Dataset()
{
delete[] Array;
}
Row &operator[](uInt32 Row){
return Array[Row];
}
uInt32 GetNoOfRows() const
{
return NRow;
}
uInt32 GetNoOfCols() const
{
return NCol;
}
Dataset<StorageType> operator*(Dataset<StorageType> const &B)
{
Dataset<StorageType> Temp(NRow,B.GetNoOfCols());
if(NCol == B.GetNoOfRows())
{
uInt32 Row = B.GetNoOfRows();
uInt32 Col = B.GetNoOfCols();
register uInt32 i, j, k;
register StorageType Product;
for(i = 0;i < NRow;i++)
{
for(j = 0;j < Col;j++)
{
Product = 0;
for(k = 0;k < Row;k++)
{
Product += Array[i][k]*B[k][j]; **--> error here**
}
Temp[i][j] = Product;
}
}
}
else
{
cerr << "Dataset::matrices aren't compatible for multiplication" << endl;
}
return (Temp);
}
void operator=(Dataset<StorageType> const &B)
{
register uInt32 i, j;
uInt32 Row = B.GetNoOfRows();
uInt32 Col = B.GetNoOfCols();
for(i = 0;i < Row;i++)
{
for(j = 0;j < Col;j++)
{
Array[i][j] = B[i][j]; **--> error here**
}
}
}
};
我收到以下错误
将 'const Dataset' 作为 'this' 参数传递会丢弃 限定符[-fpermissive]
在标记的地方 --> 这里有错误。 . 我需要使用 operator* 将调用者类中的两个数据集相乘,并且必须使用 const 参数。我该如何解决?一些代码示例会有所帮助。
【问题讨论】:
-
B参数是const,但是operator[]对非const对象进行操作。您需要第二个版本的 operator[] 返回一个 const ref,并声明一个 const 成员函数。
-
@Peter - Reinstate Monica 我需要从另一个地方调用重载的运算符,如果我从 B 参数中删除 const 我会得到另一个错误-->
cannot bind non-const lvalue reference of type Dataset<double>& to an rvalue of type DataSet<double> -
首先,如果您提取 minimal reproducible example 会有所帮助,其中包括剥离所有模板内容并使用 C++ 类型,而不是
uInt32类型定义。无论如何,请在此处搜索“基本 C++ 资源”。原因是,您的代码中有很多不良习惯可能来自不良的学习资源。例如,如果任何教程教你检查new和NULL的返回值,那么该教程完全过时或不好。 -
@UlrichEckhardt 在通过一些简单的编辑使代码编译后(更改类型 Row 的名称以避免名称冲突,包括标题),它编译得很好。这是为什么?为什么我可以在 const B 上调用非常量运算符 []? (gcc 10.2, VC.) ...godbolt.org/z/56necn4rd
标签: c++