【问题标题】:Constructors and array of object in C++C ++中的构造函数和对象数组
【发布时间】:2011-11-29 14:05:21
【问题描述】:

我正在尝试用 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;
    setAddress("NO ADDRESS GIVEN");
    amount[0]= 0.0;
    amount[1]= 0.0;
    amount[2]= 0.0;
    amount[3]= 0.0;

}


Station::Station(int c, char *ad, float a[]){

    if( (c>=1&& c<=10 ) ){
        code=c;
        address=ad;

        for(int i=0;i<4;i++){
            amount[i]=a[i]; 
        }   

    }else{

        code= 1;

        setAddress("NO ADDRESS GIVEN");
        amount[0]= 0.0;
        amount[1]= 0.0;
        amount[2]= 0.0;
        amount[3]= 0.0;
    }   
}   


Station::~Station(){

}

int main(){

    int size,code;
    char *addrr;
    addrr = (char *)(malloc(sizeof(addrr+1)));
    float mes[4];

    do{ 
        cout<<"size of array:";
        cin>>size;

    }while(size<=0 || size>=11);

    //  Station *stations= new Station[size];
    //  Station** stations = new Station*[size];
    Station stations[size];

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

        cout<<"code:";
        cin>>code;

        cout<<"address:";
        cin>>addrr;

        double amo=0;

        for(int k=0;k<4;k++){
            cout<<"values"<<k+1<<":";
            cin>>mes[k]; 
        }
    }
    /*
    for(int q=0;q<size;q++){
        stations[q].print();
    }
    */

    return 0;
}

我将从 cin 获取的值我想将它们分配给数组的对象!

【问题讨论】:

  • 给我看看数组的创建,你用new还是malloc?
  • 你可以看看上面的代码!谢谢
  • 该代码有很多问题。像内存泄漏和未定义的行为。作为可能解决大部分问题的第一步,将所有char* 的使用替换为std::string
  • 我不允许使用字符串!

标签: c++


【解决方案1】:

您可以创建默认初始化的数组,然后用想要的对象填充数组:

foo arr[10];
std::fill(arr, arr+10, foo(some, params));

或者,您可以使用 std::vector 并这样做:

std::vector<foo> arr(10, foo(some, params));

【讨论】:

    【解决方案2】:

    在 C++0x 中,你可以在 new 表达式中使用braced-init-list,这意味着你可以这样做:

    #include <iostream>
    
    class A
    {
    public:
        A(int i, int j){std::cout<<i<<" "<<j<<'\n';}
    };
    
    int main(int argc, char ** argv)
    {
        int *n = new int[3]{1,2,3};
        A *a = new A[3]{{1,2},{3,4},{5,6}};
        delete[] a;
        delete[] n;
        return 0;
    }
    

    在g++ 4.5.2下编译,使用g++ -Wall -std=c++0x -pedantic

    【讨论】:

      【解决方案3】:

      既然你说你不能使用std::string,这将变得更加困难。 addrr = (char *)(malloc(sizeof(addrr+1))); 行没有按照您的想法进行。而不是使用malloc在堆上分配,因为没有free(这将导致内存泄漏),如果我们在堆栈上分配一个预定的缓冲区大小会容易得多:char addrr[BUFFER_LENGTH]。在Station 的声明之前将BUFFER_LENGTH 定义为const int BUFFER_LENGTH = 20; 或其他适当的长度。

      要使用非默认构造函数,在 for 循环末尾添加 stations[i] = Station(c, addrr, mes); 即可。

      for(int i=0;i<size;i++){
          cout<<"code:";
          cin>>code;
      
          cout<<"address:";
          cin>>addrr; // do not read in strings longer than 20 characters or increase BUFFER_LENGTH’s size
      
          double amo=0;
      
          for(int k=0;k<4;k++){
              cout<<"values"<<k+1<<":";
              cin>>mes[k];
          }
      
          stations[i] = Station(c, addrr, mes);
      }
      

      但是,这不会正常工作,因为构造函数正在复制addrr 指针,而不是数据。我建议还将数据成员 char *address 更改为 char address[BUFFER_LENGTH]。然后,在构造函数中,您可以将行 address=ad; 替换为 strcpy(address, ad);

      注意:setAddressgetAddress 现在需要更新。

      另一条令人不安的行是Station stations[size];。这是非标准的,因为 size 在编译时不是已知的。使用Station *stations= new Station[size]; 并记住delete,或者如果您可以使用std::vector,请使用std::vector&lt;Station&gt; stations(size);

      如果你确实走std::vector 路线,使用push_back 会很好地工作:

      std::vector<Station> stations;
      
      for(int i=0;i<size;i++){
      
          cout<<"code:";
          cin>>code;
      
          cout<<"address:";
          cin>>addrr;
      
          double amo=0;
      
          for(int k=0;k<4;k++){
              cout<<"values"<<k+1<<":";
              cin>>mes[k]; 
          }
      
          stations.push_back( Station(c, addrr, mes) );
      }
      

      【讨论】:

        猜你喜欢
        • 2010-09-28
        • 2011-02-20
        • 2012-02-05
        • 1970-01-01
        • 1970-01-01
        • 2016-12-28
        • 2017-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多