【问题标题】:Error: expected constructor, destructor, or type conversion before ‘::’ token错误:“::”标记之前的预期构造函数、析构函数或类型转换
【发布时间】:2011-03-18 22:44:14
【问题描述】:

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

错误:

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 */

Matrix.cpp

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

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

ma​​in.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_H 是一个保留标识符(你不能在你的程序中使用它;它是供编译器使用的)。任何以下划线开头后跟大写字母的标识符都是保留的。考虑改用MATRIX_H_
  • 另外,Matrix::Matrix add(Matrix); 是错误的。应该是Matrix add(Matrix);。更符合标准的编译器将拒绝此类代码。

标签: c++ class templates


【解决方案1】:
Matrix::~Matrix() { } 

Matrix 是一个类模板。你得到了正确的构造函数定义;析构函数(和任何其他成员函数定义)需要匹配。

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

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

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

Matrix<int> m;

【讨论】:

  • 这行得通,但现在我收到以下内容:main.cpp:13: undefined reference to `Matrix::Matrix()'
  • 而且,正如 Oleg 正确指出的那样(为此 +1!),您不能将类模板成员函数分离到 .cpp 文件中:它们必须放在 .h 文件中。 Parashift C++ FAQ 中的更多内容
  • 啊。所以我应该只在头文件中实现整个库吗?谢谢,你似乎回答了我的大部分问题。
【解决方案2】:

定义析构函数为

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

另一个错误是你不能将类模板的实现放在 .cpp-file Template Factory Pattern in C++

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2016-03-14
    • 2014-05-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多