2015-02-19 4 views
0

Я пишу программу для своего проекта с C++; однако, я не могу добавить «предупреждение о возврате» в свой алгоритм.Как добавить «предупреждающее сообщение» в свою программу?

Мой альтромим;

#include<iostream> 

#include<conio.h> 

using namespace std; 

const int k=100; 

class safearay{ 
    int arr[k]; 

    int getel(int index){ if(index>-1 && index<k) return arr[index];}}; 

void main(void) 
{ 
    cout<<"-------------------------------------------------------------------------------\n"<<endl; 

    safearay safea1; int temp=23456; 

    for{ 
    safea1.putel(7, temp); temp=safea1.getel(7); 
    cout<<temp; 
    cout<<"\n\n !Press k to continue."<<endl<<endl; 
    }while(getch()=='k'); 
} 

Как я могу добавить раздел предупреждающих сообщений?

+0

Вы можете использовать 'throw'? – Jarod42

+0

как использовать бросок? У тебя есть какой-нибудь совет? – karen76

ответ

2

Одним из способов было бы вернуть флаг, указав, что что-то пошло не так из функции putel и напечатало ошибку в главном.

bool putel(int index, int value){ 

    if(index <= -1 || index == 10 || index > LIMIT) {//the conditions that are invalid 
     return false; 
    } 

    arr[index]=value; 
    return true; 
} 

и в главном что-то вроде этого

do{ 
    if(!safea1.putel(7, temp)){ 
     cout<<"Insert failed "<<endl; //Your warning message 
    } else { 
     temp=safea1.getel(7); 
     cout<<temp; 
     cout<<"\n\n !Press k to continue."<<endl<<endl; 
    } while(getch()=='k'); 

Я надеюсь, что это было то, что вы искали ..

1

Вы можете использовать throw, что-то вроде:

class safearray 
{ 
public: 
    void putel(int index, int value) { check_index(index); arr[index] = value;} 
    int getel(int index) const { check_index(index); return arr[index];} 

private: 
    void check_index(int index) const 
    { 
     if (index < 0 || LIMIT <= index) { 
      throw std::out_of_range("bad index " + std::to_string(index) + " for safearray"); 
     } 
    } 
private: 
    int arr[LIMIT]; 
}; 

Demo

Смежные вопросы