c++ - : expected constructor, 析构函数错误,或者 ‘::’ token 之前的类型转换

标签 c++ class templates

我在尝试编译我的类时遇到错误。

错误:

Matrix.cpp:13: 错误:在“::”标记之前需要构造函数、析构函数或类型转换

矩阵.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 */

矩阵.cpp

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

Matrix::~Matrix() { // Line 13
}

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);
}

最佳答案

Matrix::~Matrix() { } 

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

template <typename T>
Matrix<T>::~Matrix() { }

Matrix<int> m = new Matrix<int>(); 

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

Matrix<int> m;

关于c++ - : expected constructor, 析构函数错误,或者 ‘::’ token 之前的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358527/

相关文章:

c++ - 尝试使用模板扩展类时出现链接错误(LINK 2019)

c++ - 将字符串中的字符更改为数字

bool 表达式中使用的 C++ 对象/类实例

java - 在不同的方法中访问和使用自定义对象和 ArrayList<Object>

c++ - 什么是模板<typename T, T t> 习语?

c++ - 来自多行文件 C++ 的 vector 矩阵

c++ - 我可以让 gcc 链接器创建一个静态库吗?

c++ - 不兼容的类声明 c++

templates - 排序 Velocity 模板中的对象列表 - Liferay

c++ - 在模板类中为特定类型编写比较函数