c++类的编写

要主要的几个特殊的函数:

1、构造函数,

2、复制构造函数,

3、拷贝构造函数

//以上三个函数,会默认创建,但是当用户定义的时候会取消默认的创建。

4、常对象的函数,

5、可变对象的函数,

//在对象变量可以变化的时候,只有5;在对象变量不变的时候,只有4,

可以参考的代码:

#ifndef MATRIX_H
#define MATRIX_H

#include <vector>

using namespace std;

template <typedef Object>
class matrix
{
public:
matrix( int rows, int cols ) : array( rows )//构造函数
{
for( int i = 0; i < rows; i++ )
array[ i ].resize( cols );
}
matrix( const matrix & rhs ) : array( rhs.array ) { }//拷贝构造函数

matrix & operator = (const matrix & rhs) //复制构造函数
{
if(this == &rhs)
{
return *this;
}
this->array = rhs.array;
return *this;
}

const vector<Object> & operator[]( int row ) const
{ return array[ row ]; }

vector<Object> & operator[]( int row )
{ return array[ row ]; }

int numrows( ) const
{ return array.size( ); }
int numcols( ) const
{ return numrows( ) ? array[ 0 ].size( ) : 0; }
private:
vector< vector<Object> > array;
};

#endif

原文地址:https://www.cnblogs.com/haibianxiaolu/p/4513514.html