2013-10-13 19 views
-1

我有這個向量類,並且提供了一個驅動程序來測試這個類。大部分似乎很好地工作,但我覺得有什麼不對的例外部分(我還沒有完全充分的理解)如何在向量類中使用異常和指針

下面是類.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; 
} 

任何幫助表示讚賞。由於

+1

你爲什麼試圖在已有'std :: vector'的時候實現自己的向量? – LihO

+2

壓痕在哪裏? – Arpit

+1

請不要發佈*全部*代碼,只發布與手頭問題相關的部分。在這種情況下,代碼拋出異常並且代碼捕獲它們。另外*你有什麼樣的問題?拋出異常時會發生什麼?你期望會發生什麼? –

回答

1

您所提供的驅動程序:

try { 
    cout << sam.at(i) << " "; 
} 
catch(int badIndex) { 
    cout << "\nOut of bounds at index " << badIndex << endl; 
} 

預計int將被拋出(有點怪異的設計,但好...這是一個將使用你的類的代碼...)。你的實現at()可能是這樣的:

int& myVector::at(int i) throw(int) { 
    if (i < vsize) 
     return array[i]; 
    throw i; 
} 

只是儘量遵循一個簡單的規則:擲按值,漁獲參考


還要注意的是,你有一個指針:

private: 
    int* array; 

指向動態分配的內存中構造分配和拷貝構造函數析構函數釋放:

myVector::myVector(int i) 
{ 
    ... 
    array = new int[maxsize]; 
} 
myVector::myVector(const myVector& v)//copy constructor 
{ 
    ... 
    array =new int[maxsize]; 
} 
myVector::~myVector() 
{ 
    delete[] array; 
} 

但是如何處理賦值運算符?請參閱What is The Rule of Three?

0

您的停止條件for循環在最後一個循環結束後一個元素結束(即由於只有三個元素,您無法訪問第4個元素的sam矢量)。

std::vector::at投擲std::out_of_range異常在這種情況下(見:http://en.cppreference.com/w/cpp/container/vector/at),而不是int之一。所以你應該改變你的異常處理部分,如下所示:

#include <exception> 

try 
{ 
     cout << sam.at(i) << " "; 
} 
catch(std::out_of_range exc) 
{ 
    cout << "\nOut of bounds at index " << exc.what() << endl; 
}