首页 > 解决方案 > 调用对象指针的成员函数时程序崩溃

问题描述

正如标题所说,每当我尝试调用 getter 函数以返回向量中的对象指针中的私有变量的值时,它都会崩溃。这导致我的其他 2 个功能无用。我知道 command == display 和 command == summary 不能正常工作。我做了一些调试,发现每当我尝试 cout<<P_obj[i]->getnumber() 时,我都会崩溃。这是我的代码:

#include <string>
#include <cstdlib>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <vector>
#include <cstdio>
using namespace std;

class stock {
private:
    int sharenumber;
    float shareprice;
    string sharename;

public:
    stock(int x, string y,float z)
    :sharenumber(x),sharename(y),shareprice(z)
    {
    }

    int returnnumber(){
    return sharenumber;
    }

    string returnname(){
    return sharename;
    }

    float returnprice(){
    return shareprice;
    }
};



bool ispositive(int x){
    bool a = false;
    if (x>0){a = true;}
    return a;
}
void buy(vector <stock*> list,int size){
     int amount;
    float price;
    string symbol;

   cout<<"Please enter the number of shares, the share symbol and the price of the share to make your purchase.\n";


                do{
                cout<<"Enter the amount: ";
                cin>>amount;
                if (ispositive(amount)==false){
                    cout<<"Please enter a positive number for the amount!\n";
                }
                }while(ispositive(amount)==false);

                cout<<"Enter the symbol: ";
                cin>>symbol;

               do{
                cout<<"Enter the stock price: $ ";
                cin>>price;
                if (ispositive(price)==false){
                    cout<<"Please enter a positive number for the price!\n";
                }
                }while(ispositive(price)==false);

               list.push_back(new stock(amount,symbol,price));
                cout<<"Your purchase has been made. Thank you for your time.\n\n";


}

void summary(vector <stock*> list,int size){
   float cost = 0;
   int stocktotal = 0;
    for (int i = 0; i < size;i++){
        cost = cost + (list[i]->returnprice()*list[i]->returnnumber());
        stocktotal = stocktotal + list[i]->returnnumber();
    }
    cout<<"\nUser has made "<<size<<" purchases in total. The total number of stocks bought is "<<stocktotal<<". The total cost is "<<cost<<"."<<endl<<endl;
}

int main(int argc, char *argv[])
{

    vector <stock*> P_obj;
    bool cont = true;
    bool last_cont = true;
    char * check;
    bool signal = false;
    string command;
    char done;


    if (argc>1){

        check = strstr(argv[1],".txt");


        if (check!= NULL){
                fstream tester;
                tester.open(argv[1]);
        if (tester.is_open()){
                signal=true;}
        }else{cout<<"Error has occurred. Please enter correct data file name with .txt extension.";}

        if (signal){

            cout<<"\nWelcome to the Golden Sacks! Enter a command to start your stock trading career.\n\n";
            ofstream user_data(argv[1]);

            while(cont==true){
            bool e_valid = false;

            cout<<"Enter command here: ";
            cin>>command;

            if (command == "buy"){
                buy(P_obj,P_obj.size());
            }

            if (command == "summary"){
                summary(P_obj,P_obj.size());
            }

            if (command == "display"){
                cout<<"\nList of all purchases:\n";
                for (int y = 0; y < P_obj.size(); y++){
                    cout<<P_obj[y]->returnnumber()<<" "<<P_obj[y]->returnname()<<" "<<"$"<<fixed<<setprecision(2)<<P_obj[y]->returnprice()<<endl;
                }
                cout<<endl;
            }

            if (command=="help"){
            cout<<"Command list:\n";
            cout<<left<<setw(2)<<"- buy\n";
            cout<<left<<setw(2)<<"- display\n";
            cout<<left<<setw(2)<<"- summary\n";
            cout<<left<<setw(2)<<"- find <stock-symbol>\n";
            cout<<left<<setw(2)<<"- amount>= <purchase-amount>\n";
            cout<<left<<setw(2)<<"- help\n";
            cout<<left<<setw(2)<<"- exit\n\n\n";
            }

            if (command == "exit"){
                while (last_cont == true){
                cout<<"Are you sure you want to quit? (Yy/Nn):";
                cin>>done;
                if (done == 'Y'||done == 'y'||done =='N'||done =='n'){
                       last_cont=false;
                       if(done=='Y'||done=='y'){
                            cont = false;
                            cout<<"Thank you for using Golden Sacks. We hope to see you soon!\n";
                        }
                }else {cout<<"Please enter only Y|N or y|n, try again.\n\n";}
              }
            }

          }  //end of loop
            for (int i = 0; i < P_obj.size(); i++){
                user_data<<P_obj[i]->returnnumber()<<" "<<P_obj[i]->returnname()<<" "<<"$"<<fixed<<setprecision(2)<<P_obj[i]->returnprice()<<endl;
            }
        }


    }else {cout<<"Too few arguments, enter a data file name with .txt extension to continue";}

}

标签: c++vector

解决方案


矢量<股票*> P_obj;没有正确分配。//内存泄漏库存不是用户定义的类型,如 int 或 double。

因此,如果您将它用作指针,请使用 RAII 技术,在它的解构中释放它

例如:

类 Stock{ int* x{nullptr}; public: Stock(...);//在这里分配 ~Stock(..);//在这里解除分配 };

您可以进一步定义新的和删除的运营商


推荐阅读