我有這個向量類,並且提供了一個驅動程序來測試這個類。大部分似乎很好地工作,但我覺得有什麼不對的例外部分(我還沒有完全充分的理解)如何在向量類中使用異常和指針
下面是類.cpp文件的代碼
int myVector::at(int i)
{
if(i<vsize)
return array[i];
throw 10;
}
和這裏是驅動代碼
#include "myVector.h"
#include <iostream>
using namespace std;
int main()
{
// Create a default vector (cap = 2)
myVector sam;
// push some data into sam
cout << "\nPushing three values into sam";
sam.push_back(21);
sam.push_back(31);
sam.push_back(41);
cout << "\nThe values in sam are: ";
// test for out of bounds condition here
for (int i = 0; i < sam.size() + 1; i++)
{
try
{
cout << sam.at(i) << " ";
}
catch(int badIndex)
{
cout << "\nOut of bounds at index " << badIndex << endl;
}
}
cout << "\n--------------\n";
// clear sam and display its size and capacity
sam.clear();
cout << "\nsam has been cleared.";
cout << "\nSam's size is now " << sam.size();
cout << "\nSam's capacity is now " << sam.capacity() << endl;
cout << "---------------\n";
// Push 12 values into the vector - it should grow
cout << "\nPush 12 values into sam.";
for (int i = 0; i < 12; i++)
sam.push_back(i);
cout << "\nSam's size is now " << sam.size();
cout << "\nSam's capcacity is now " << sam.capacity() << endl;
cout << "---------------\n";
cout << "\nTest to see if contents are correct...";
// display the values in the vector
for (int i = 0; i < sam.size(); i++)
{
cout << sam.at(i) << " ";
}
cout << "\n--------------\n";
cout << "\n\nTest Complete...";
cout << endl;
system("PAUSE");
return 0;
}
任何幫助表示讚賞。由於
你爲什麼試圖在已有'std :: vector'的時候實現自己的向量? – LihO
壓痕在哪裏? – Arpit
請不要發佈*全部*代碼,只發布與手頭問題相關的部分。在這種情況下,代碼拋出異常並且代碼捕獲它們。另外*你有什麼樣的問題?拋出異常時會發生什麼?你期望會發生什麼? –