c++ - 模板类和类属性也是模板

标签 c++ templates operator-overloading

我在编译以下 header 时遇到问题。这是我第一次使用模板,我想我弄错了。编译器将错误指向 vector<vector<T>> data_;和运算符重载函数。我想要 data_ vector 与 OptBaseMatrix 具有相同的类型对象,但我不确定该怎么做......我真的不知道如何解决这个问题。帮助!

#ifndef OPTBASEMATRIX_H
#define OPTBASEMATRIX_H

#include <vector>

template<typename T>
class OptBaseMatrix 
{ 
public:
 vector<vector<T>> data_; 

 OptBaseMatrix(int rows, int cols);
 ~OptBaseMatrix();

 void readMatrix();
 void printMatrix();
 int getRows();
 int getCols();

    OptBaseMatrix<T> operator+(const OptBaseMatrix<T>& matrix1, const OptBaseMatrix<T>& matrix2);

private:
 int rows_; 
 int cols_; 
};

#endif // OPTBASEMATRIX_H

更新:这是调试器日志的片段:

Error   1   error C2143: syntax error : missing ';' before '<'  optbasematrix.h 17  TD2
Error   2   error C4430: missing type specifier - int assumed. Note: C++ does not support default-int   optbasematrix.h 17  TD2

我试过修改 vector > data_;按 vector >数据_;仍然得到同样的错误:/我在某处读到我的模板类头文件 (.h) 和实现文件 (.cpp) 必须在同一个文件中...这可能相关吗?

更新 2:哇!我忘记了“使用命名空间标准;”。问题现在似乎已解决!

最佳答案

你需要在两个>之间放置一个空格

 vector<vector<T> > data_;

没有空格,>>> 被视为流提取/右移运算符。

此外,您需要将 operator+ 声明为一个自由函数,或者您必须仅使用一个参数声明它:

// Member function
Matrix<T> operator+(const Matrix<T>& other) const;

// Free function (`friend` makes the function free
// even though it's declared within the scope of the class definition)
friend Matrix<T> operator+(const Matrix<T>& lhs, const Matrix<T>& rhs);

关于c++ - 模板类和类属性也是模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2186230/

相关文章:

c++ - C++ 中 try/catch block 的使用

使用条件变量的 C++ 监视器类/包装器

c# - 有没有办法从非 Web 应用程序处理 MVC View (aspx 文件)?

c++ - 推导元组的类型

c++ - 有没有办法重载 operator= 以对右侧的函数具有特定行为

c++ - 我是否需要重载类的强制转换运算符?

c++ - 这是什么意思?

c++ - 尝试打印时堆损坏

C++ 管道错误,pipe_wait 永远

C++ 模板特化改变了 constexpr 规则?