首页 文章

在范围内声明向量

提问于
浏览
2

在我的In-Progress BigInt类中,我在向量声明方面遇到了麻烦 . 我收到错误:

prog.cpp:在函数'void setBig1(std :: string,int)'中:prog.cpp:45:3:错误:'big1'未在此范围内声明big1.push_back(dig [x]); ^ prog.cpp:在函数'voidgetBig1(int)'中:prog.cpp:50:11:错误:'big1'未在此范围内声明cout << big1 [x];

我相信我的getter和setter涉及向量big1并没有认识到类定义的'public:'部分中向量的去除 . 但我找不到错误的解决方案或明确原因 . 我的代码如下:

//my bigInt class
#include <iostream>
#include <vector>
#include <string>
using namespace std;
//class, constructors
//overload operators methods
//add, subtract, multiply, divide
class bigInt{//class
    public:
        bigInt();
        ~bigInt();
        void setString(string dig);
        string getString(void);
        int getDigitLength(void);
        std::string digit;
        int digitLength;
        std::string digString;
        void setBig1(string dig, int dLength);
        std::vector<int> big1;
        std::vector<int> big2;
        void getBig1(int dLength);
};
//constructors
bigInt::bigInt(void){
    std::vector<int> big1;
}
//deconstructor
bigInt::~bigInt(){

}
//getters/setters
void bigInt::setString(string dig){
    digit= dig;
    digitLength= (digit.length());
}
string bigInt::getString(){
    return digit;
}
int bigInt::getDigitLength(){
    return digitLength;
}
void setBig1(string dig, int dLength){
    for(int x= 0; x<(dLength); x++)     
    {
        big1.push_back(dig[x]);
    }
}
void getBig1(int dLength){
    for(int x= 0; x<(dLength); x++){
        cout << big1[x] ;
    }

}

int main(){
    string digString= "1"; //string
    bigInt my_int{};
    //bigInt big1<int>;
    my_int.setString(digString); //setInternalString to equal digString
    cout << my_int.getString() << endl; //prints internal string
    my_int.setBig1(my_int.getString(), my_int.getDigitLength());//sets big1 vector = to string
    my_int.getBig1(my_int.getDigitLength()); //print big1 vector

}

我非常感谢任何帮助 .

1 回答

  • 2

    您忘记指定定义成员函数的类 . 代替

    void setBig1(string dig, int dLength){
        for(int x= 0; x<(dLength); x++)     
        {
            big1.push_back(dig[x]);
        }
    }
    void getBig1(int dLength){
        for(int x= 0; x<(dLength); x++){
            cout << big1[x] ;
        }
    

    void bigInt::setBig1(string dig, int dLength){
        for(int x= 0; x<(dLength); x++)     
        {
            big1.push_back(dig[x]);
        }
    }
    void bigInt::getBig1(int dLength){
        for(int x= 0; x<(dLength); x++){
            cout << big1[x] ;
        }
    

    此外,您可以使用限定符const声明所有getter,因为它们不会更改类本身的对象 . 例如

    class bigInt
    {
    //...
    
        void getBig1(int dLength) const;
    };
    
    void bigInt::getBig1(int dLength) const
    {
        for ( int i = 0; i < dLength; i++ ) cout << big1[i] ;
    }
    

    并且在一般情况下,而不是类型int,最好至少使用type size_t或std :: vector :: size_type

    可以使用访问控制私有声明向量本身 .

相关问题