矢量给出垃圾值

时间:2015-02-03 15:06:17

标签: c++ vector

我无法理解为什么我会得到垃圾值...我不知道如何让它给我设置的值而不分离setdetails函数。

我不太确定问题是使用循环还是使用set方法,我尝试使用几乎代码的每个部分,但我仍然得到相同的垃圾值......我想我错过了一些事情

 class Book
{

    int isbn;
    int price;

public: 

Book();
Book(int isbn,int price){

    isbn =0;
    price = 0;
}

void setDetails(int isbn,int price){
    this->isbn = isbn;
    this->price = price;
}


int getDetails()const{
    return isbn;
    return price;
}};

void fillvector(vector<Book>& mybook){

cout <<"how many books do you want to add ?"<<endl;
int loop;
int Isbn;
int Price;
cin>> loop;

for (int i=0; i < loop; i++){

    cout<<"ISBN : ";
    cin>> Isbn;
    cout<<endl;
    cout<<"price : ";
    cin >>Price;

    Book newbook(Isbn,Price);
    mybook.push_back(newbook);
}

}
void printvector(vector<Book>& mybook)    {

int size = mybook.size();

for (int i = 1; i <size; i++){

    cout<< "ISBN : "<< mybook[i].getDetails()<<endl;


}

}

main(){
    vector<Book> mybook;

    fillvector(mybook);
    printvector(mybook);

return 0;
}

2 个答案:

答案 0 :(得分:3)

在您的构造函数中,当您使用与您的成员相同的名称时,您必须添加this->

Book(int isbn, int price) {
    this->isbn = isbn;
    this->price = price;
}

Book(int isbn, int price) :
    isbn(isbn),
    price(price)
{
}

答案 1 :(得分:3)

你有一些不同的错误。其中一个导致代码输出垃圾。查看带有注释的更正版本。

class Book
{

    int isbn;
    int price;

public: 

Book();
// Arguments are named same as members!
// This cause members to be uninitialized (i.e. contain garbage)
Book(int arg_isbn,int arg_price){

    isbn =arg_isbn;
    price = arg_price;
}

void setDetails(int arg_isbn,int arg_price){
    isbn = arg_isbn;
    price = arg_price;
}

// You cannot return two values this way! Only one at time.
// So, implement two methods returning each particular detail
int get_isbn()const{
    return isbn;
}
int get_price()const{
    return price;
}
};

void fillvector(vector<Book>& mybook){

cout <<"how many books do you want to add ?"<<endl;
int loop;
int Isbn;
int Price;
cin>> loop;

for (int i=0; i < loop; i++){

    cout<<"ISBN : ";
    cin>> Isbn;
    cout<<endl;
    cout<<"price : ";
    cin >>Price;

    Book newbook(Isbn,Price);
    mybook.push_back(newbook);
}

}
void printvector(vector<Book>& mybook)    {

int size = mybook.size();
// for loop was starting from 1, this seem not intended
for (int i = 0; i <size; i++){
    cout<< "ISBN : "<< mybook[i].get_isbn() << endl;
    // Output of price member could be added here
}

}

main(){
    vector<Book> mybook;

    fillvector(mybook);
    printvector(mybook);

return 0;
}

PS。一些违规风格是孤立的。