小编gro*_*ron的帖子

C++中的构造函数和对象数组

我正在尝试用C++创建一个应用程序.在应用程序中,我有默认构造函数和另一个带有3个参数的构造函数.用户从键盘提供一个整数,它将用于使用非默认构造函数创建对象数组.不幸的是,到目前为止我还没有完成它,因为我遇到了创建对象数组的问题,他们将使用非默认构造函数.有什么建议或帮助吗?

#include<iostream>
#include<cstring>
#include<cstdlib>
#include <sstream>

using namespace std;

class Station{

public:
    Station();
    Station(int c, char *ad, float a[]);    
    ~Station(); 


    void setAddress(char * addr){

        char* a;
        a = (char *)(malloc(sizeof(addr+1)));
        strcpy(a,addr);
        this->address = a;
    }

    void setCode(int c){
        code=c; 
    }

    char getAddress(){
        return *address;
    }

    int  getCode(){
        return code;
    }


    float getTotalAmount(){
        float totalAmount=0;
        for(int i=0;i<4;i++){
            totalAmount+=amount[i];
        }
        return totalAmount;
    }

    void print(){

        cout<<"Code:"<<code<<endl;
        cout<<"Address:"<<address<<endl;
        cout<<"Total Amount:"<<getTotalAmount()<<endl;
        cout<<endl;
    }


private:
    int code;
    char *address;
    float amount[4];

};


Station::Station(){
    code= 1; …
Run Code Online (Sandbox Code Playgroud)

c++

5
推荐指数
1
解决办法
3万
查看次数

标签 统计

c++ ×1