错误:在'::'标记之前的预期构造函数,析构函数或类型转换

Cha*_*Ray 0 c++ templates class

我在尝试编译我的课时遇到错误.

错误:

Matrix.cpp:13:错误:在'::'标记之前的预期构造函数,析构函数或类型转换

Matrix.h

#ifndef _MATRIX_H
#define _MATRIX_H

template <typename T>
class Matrix {
public:
    Matrix();
    ~Matrix();
    void set_dim(int, int);     // Set dimensions of matrix and initializes array
    unsigned int get_rows();    // Get number of rows
    unsigned int get_cols();    // Get number of columns
    void set_row(T*, int);      // Set a specific row with array of type T
    void set_elem(T*, int, int);// Set a specific index in the matrix with value T
    bool is_square();           // Test to see if matrix is square
    Matrix::Matrix add(Matrix); // Add one matrix to another and return new matrix
    Matrix::Matrix mult(Matrix);// Multiply two matrices and return new matrix
    Matrix::Matrix scalar(int); // Multiply entire matrix by number and return new matrix

private:
    unsigned int _rows;         // Number of rows
    unsigned int _cols;         // Number of columns
    T** _matrix;                // Actual matrix data

};

#endif  /* _MATRIX_H */
Run Code Online (Sandbox Code Playgroud)

Matrix.cpp

#include "Matrix.h"
template <typename T>
Matrix<T>::Matrix() {
}

Matrix::~Matrix() { // Line 13
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include <stdlib.h>
#include <cstring>
#include "Matrix.h"

int main(int argc, char** argv) {
    Matrix<int> m = new Matrix<int>();
    return (EXIT_SUCCESS);
}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 6

Matrix::~Matrix() { } 
Run Code Online (Sandbox Code Playgroud)

Matrix是一个类模板.你有正确的构造函数定义; 析构函数(以及任何其他成员函数定义)需要匹配.

template <typename T>
Matrix<T>::~Matrix() { }
Run Code Online (Sandbox Code Playgroud)
Matrix<int> m = new Matrix<int>(); 
Run Code Online (Sandbox Code Playgroud)

这不行. new Matrix<int>()产生一个Matrix<int>*,你无法初始化a Matrix<int>.这里不需要任何初始化程序,下面将声明一个局部变量并调用默认构造函数:

Matrix<int> m;
Run Code Online (Sandbox Code Playgroud)