C++ 模板化类定义 - 不同类的模板化返回类型

标签 c++ arrays class templates

template <class T>
Row<T> Array2D<T>::operator[](int index) const
{

}

此代码无效,给出错误“声明与“Array2D::Row Array2D::operator[](int index) const”不兼容”(在第 19 行声明)。我正在使用 2 个模板类,并且我认为这是主要问题,但我不确定它是如何解决的。感谢任何帮助,如果我需要更多详细信息,请告诉我。谢谢。

类声明:

#pragma once
#include "Array.h"
#include "Row.h"

template <class T>

class Array2D
{
template <class T> class Row;

public:
    Array2D();
    Array2D(int row, int col);
    Array2D(const Array2D & copy);

    ~Array2D();

    Array2D & operator =(const Array2D & rhs);
    Row<T> operator[](int index) const;

    int getRow() const;
    void setRow(int rows);
    int getColumns() const;
    void setColumns(int columns);

    T & Select(int row, int column);

private:
    Array<T> m_array;
    int m_row;
    int m_col;
};

行类:

#pragma once

#include "Array2D.h"

template <class T>

class Row
{
template <class T> class Array2D;

public:
    Row(Array2D<T> & array, int row);
    T & operator[](int column);

private:
    Array2D<T> & m_array2D;
    int m_row;

};

template <class T>
Row<T>::Row(Array2D<T> & array, int row)
{

}

template <class T>
T & Row<T>::operator[](int column)
{

}

最佳答案

如果你写

template <class T>
class Array2D
{
template <class T> class Row;

 // ...
};

你说 Row 是定义在 inside Array2D 中的模板类。

写的时候也一样

template <class T>
class Row
{
template <class T> class Array2D;

// ...
};

你说 Array2D 是在 Row 中定义的模板类。

我想你打算将 RawArray2D 声明为独立的类,所以类似于

template <class T>
class Row;

template <class T>
class Array2D
{
  // ...
};

template <class T>
class Array2D;

template <class T>
class Row
{    
  // ...
};

关于C++ 模板化类定义 - 不同类的模板化返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54192022/

相关文章:

c++ - 为什么 argc 返回 6 而不是 3?

javascript - 在 javascript/Angular 中创建播放列表(按值复制数组,但按引用设置嵌套对象)

C++ 释放结构使用的所有内存

c++ - object *operator<<(object* one, type& two);

c++ - 使用指针时 const 以什么方式干扰标记更专门的模板?

php - 如何在 $_SESSION 中存储和检索错误数组

php - 检查数组中的值

Python:对象没有属性错误:一个数组

java - 何时在匿名类中创建方法

c++ - 如何将转换应用于条件运算符中的位字段类型?