C++ 有出现问题了,小问题,帮忙看看!

Timor君 发布于 2012/06/17 18:03
阅读 186
收藏 0

代码如下:

#include <iostream>
#include <cassert>
using namespace std;

template <typename element_type>
class MinVector 
{
public:
	MinVector(int initSize = 0): m_capacity(INIT_CAPACITY)
	{
		m_size = initSize;
		m_pElem = new element_type[m_capacity];
	}
	~MinVector()
	{ delete []m_pElem; m_pElem = NULL;}

	MinVector(const MinVector &vec)
	{
		m_pElem = new element_type[vec.m_capacity];
		for ( int i = 0; i < vec.get_size(); i++)
			m_pElem[i] = vec.at(i);
		m_size = vec.m_size;
		m_capacity = vec.m_capacity;
		
	}

	MinVector& operator=(const MinVector &vec)
	{		
		delete m_pElem;
		
		m_pElem = new element_type[vec.m_capacity];
		for ( int i = 0; i < vec.get_size(); i ++)
			m_pElem[i] = vec.at(i);
		m_size = vec.m_size;
		m_capacity = vec.m_capacity;
		
		return *this;
		
	}

	element_type& operator[] (int index) { return m_pElem[index];}

	int get_size() const { return m_size;}
	int get_capacity() const { return m_capacity;}

	int at(int index) 
	{
		assert(index < m_size);
		return m_pElem[index];
	}
	int at(int index) const { assert(index < m_size); return m_pElem[index];}

	void clear() 
	{
		delete m_pElem;
		m_pElem = new element_type[INIT_CAPACITY];
		m_size = 0;
		m_capacity = INIT_CAPACITY;
	}

	void resize(int size = 0)
	{
		if (size > m_capacity)
			reserve(size);
		m_size = size;
		 
	}

	void reserve(int capacity ) 
	{
		assert(capacity > m_capacity);
		
		element_type* old_p =  m_pElem;
		
		m_pElem = new element_type[capacity];
		for ( int i = 0; i < get_size(); i++)
			m_pElem[i] = old_p[i];	
		
		delete old_p;
		m_capacity = capacity;

	}

	void swap( MinVector& vec)
	{
		std::swap<element_type*>(m_pElem, vec.m_pElem);
		std::swap<int>(m_size, vec.m_size);
		std::swap<int>(m_capacity, vec.m_capacity);
		
	}
	bool empty() const { return m_size == 0; }

private:
	enum{ INIT_CAPACITY = 10};
	
	element_type  *m_pElem;
	int           m_size;
	int           m_capacity;
	
};

int main()
{
	MinVector<int> a(3);
	a[0] = 0;
	a[1] = 1;
	a[2] = 2;

	MinVector<int> b(4);
	a[0] = 3;
	a[1] = 2;
	a[2] = 1;
	b.swap(a);


	cout << a.get_size() << endl;
	cout << a.get_capacity() << endl;

	cout << a.at(0) << endl;
	cout << a.at(1) << endl;
	cout << a.at(2) << endl;
	//cout << a.at(3) << endl;

	cout << b.get_size() << endl;
	cout << b.get_capacity() << endl;
	
	cout << b.at(0) << endl;
	cout << b.at(1) << endl;
	cout << b.at(2) << endl;

	return 0;
}


 

 在vc6.0下编译,结果不是我希望的。


 在执行 swap函数时,发现数据并没有交换,问题出在哪里呢?
截图如下:


加载中
0
Timor君
Timor君

a[0] = 3;
111 a[1] = 2;
112 a[2] = 1;


b.swap(a);

这里我写错了,本来是 
b[0] = 3;
b[1] = 2;
b[2] = 1;

返回顶部
顶部