我在编译以下标头时遇到问题。这是我第一次使用模板,我想我弄错了。编译器将错误指向 vector> 。 data_;
和运算符重载函数。我希望 data_
向量与 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
我尝试修改向量>数据_;按矢量>数据_;仍然得到相同的错误:/我在某处读到我的模板类头(.h)和实现(.cpp)必须位于同一个文件中...这可能相关吗?
更新2:哇!我忘记了“使用命名空间 std;”。现在问题似乎已经解决了!
I'm having trouble compiling the following header. It's my first experience with templates and I guess I'm getting something wrong. The compilers point errors at vector<vector<T>> data_;
and the operator overloading function. I would like the data_
vector to have the same type as the OptBaseMatrix
object but I'm not sure how to do it... I really don't know how to solve this problem. Help!
#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
UPDATE: Here is a snippet from the debugger log:
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
I've tried modifying vector> data_; by vector > data_; and still get the same error :/ I read somewhere that my template class header (.h) and implementation (.cpp) must be in the same file... is this possibly related ?
UPDATE 2: Wow ! I had forgotten "using namespace std;". The problem seems fixed now !
发布评论
评论(2)
您需要在两个
>
之间放置一个空格。如果没有空格,
>>
将被视为流提取/右移运算符。此外,您需要将
operator+
声明为自由函数,或者必须仅使用一个参数来声明它:You need to put a space between the two
>
.Without the space,
>>
is treated as a stream-extraction/right-shift operator.Additionally, you either need to declare
operator+
as a free function or you must declare it with one parameter only:尝试:
Try: