0

我有一个带有变量参数列表的构造函数。它工作正常。除非有人输入错误数量的参数,否则它会发疯。当他们这样做时,我怎么能抓住?由于程序信任用户输入正确数量的变量,我不确定。

VecXd.hpp:

#ifndef JF_VecXd
#define JF_VecXd

#include <iostream>
#include <stdarg.h>

template <class T>
class VecXd{
    public: 
        VecXd(int num, ...);   
        void display();


        private:
            int size;
            T * elements;

};

template <class T> 
VecXd<T>::VecXd(int num, ...):size(num){
    va_list argP; 
    va_start(argP, num);
    elements = new T[size];
    for(int n = 0; n < size; n++)
        elements[n] = va_arg(argP,T);
    va_end(argP);
}

template <class T>
void VecXd<T>::display(){
    std::cout << "Vector size is " << size << "\n";
    for(int n = 0; n < size; n++)
        std::cout << "element " << n << ": " << elements[n] << "\n";
}  

#endif

vTest.cpp:

#include "vecxd.hpp"
#include <iostream>

int main(){

    VecXd<int> v2(5,1,2,3,4,5);    // correct number of args
    VecXd<int> v1(8,1,2,3,4,5);    // incorrect number of args
                                  //I don't know how to catch this error


    std::cout << "Vector 1:" << std::endl; 
    v1.display();

    std::cout << "Vector 2:" << std::endl; 
    v2.display();

    return 0;
}
4

0 回答 0