继承时访问父类数据?
贴代码:
- C/C++ code
#ifndef MATRIX_H_#define MATRIX_H_#include <cstring>namespace aes {/* AES过程中用到一些矩阵, 这是通用的表现形式. * */template<typename T, int EDGE_SIZE>class Matrix {public: Matrix(); Matrix(const Matrix<T, EDGE_SIZE>&); virtual ~Matrix() {}; virtual Matrix<T, EDGE_SIZE> &operator=(const Matrix<T, EDGE_SIZE>&); /* 取值 * */ T get(int rowIndex, int columnIndex) const; /* 设值. * */ void set(int rowIndex, int columnIndex, const T &value);protected: T data[EDGE_SIZE * EDGE_SIZE]; int data_value;private: static int indexFromRowAndColumn(int rowIndex, int columnIndex);};} /* namespace aes */#endif- C/C++ code
#include <stdexcept>#include "Matrix.h"namespace aes {template<typename T, int EDGE_SIZE>Matrix<T, EDGE_SIZE>::Matrix() {}template<typename T, int EDGE_SIZE>Matrix<T, EDGE_SIZE>::Matrix(const Matrix<T, EDGE_SIZE> &matrix) { for(int i = 0; i < EDGE_SIZE * EDGE_SIZE; ++i) this->data[i] = matrix.data[i];}template<typename T, int EDGE_SIZE>Matrix<T, EDGE_SIZE> &Matrix<T, EDGE_SIZE>::operator =(const Matrix<T, EDGE_SIZE> &matrix) { if(&matrix == this) return *this; for(int i = 0; i < EDGE_SIZE * EDGE_SIZE; ++i) this->data[i] = matrix.data[i]; return *this;}template<typename T, int EDGE_SIZE>T Matrix<T, EDGE_SIZE>::get(int rowIndex, int columnIndex) const { int i = indexFromRowAndColumn(rowIndex, columnIndex); if(i < 0 || i >= EDGE_SIZE * EDGE_SIZE) throw std::out_of_range("Matrix out of range."); return data[i];}template<typename T, int EDGE_SIZE>void Matrix<T, EDGE_SIZE>::set(int rowIndex, int columnIndex, const T &value) { int i = indexFromRowAndColumn(rowIndex, columnIndex); if(i < 0 || i >= EDGE_SIZE * EDGE_SIZE) throw std::out_of_range("Matrix out of range."); data[i] = value;}} /* namespace aes */- C/C++ code
#ifndef INTMATRIX_H_#define INTMATRIX_H_#include "Matrix.h"namespace aes {template<int EDGE_SIZE>class IntMatrix: public Matrix<int, EDGE_SIZE> {public: IntMatrix();// IntMatrix(const IntMatrix&);// IntMatrix &operator=(const IntMatrix&);private:};} /* namespace aes */#endif- C/C++ code
#include <cstring>#include "IntMatrix.h"namespace aes {template<int EDGE_SIZE>IntMatrix<EDGE_SIZE>::IntMatrix() { memset(data, EDGE_SIZE * EDGE_SIZE, 0); [u][b][color=#FF0000]//这里, error: 'data_value' was not declared in this scope[/color][/b][/u]}} /* namespace aes */编译之后.
IntMatrix.cpp: In constructor 'aes::IntMatrix<EDGE_SIZE>::IntMatrix()':
IntMatrix.cpp:8:2: error: 'data_value' was not declared in this scope
[解决办法]
模板类的实现和定义在一块,不要分开写
分开写的我只见过一个,很奇怪的写法:在头文件中的尾部加上#include "matrix.cpp"
不过这种很怪
[解决办法]
在头文件中的尾部加上#include "matrix.cpp"
就是将cpp文件引入到头文件中
其实就是模板声明和实现不能分开,因为模板的类型是运行的时候才确定的。