C++中的构造函数和对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8312054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Constructors and array of object in C++
提问by gron gron
I'm trying to create an application in C++. In the application I have the default constructor and another constructor with 3 arguments. The user is providing from the keyboard an integer that it will be used to create an array of objects using the non default constructor. Unfortunately I haven't been able to finish it till now, since I'm having issues with the creation of the array of objects that they will use the non default constructor. Any suggestions or help?
我正在尝试用 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;
}
the values that I'll take from cin
I want to assign them to the objects of the array!
我将从中获取的值cin
我想将它们分配给数组的对象!
回答by reko_t
You can either create the array default-initialized and then fill the array with the wanted object:
您可以创建默认初始化的数组,然后用所需的对象填充数组:
foo arr[10];
std::fill(arr, arr+10, foo(some, params));
Alternatively you could use std::vector
and do just:
或者,您可以使用std::vector
并执行以下操作:
std::vector<foo> arr(10, foo(some, params));
回答by fefe
In C++0x, you can use braced-init-list
in new expression, which means you can do this:
在 C++0x 中,您可以使用braced-init-list
in new 表达式,这意味着您可以这样做:
#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;
}
Compiled under g++ 4.5.2, using g++ -Wall -std=c++0x -pedantic
在 g++ 4.5.2 下编译,使用 g++ -Wall -std=c++0x -pedantic
回答by Tyler Hyndman
Since you say you can't use std::string
, this is going to be much more difficult. The line addrr = (char *)(malloc(sizeof(addrr+1)));
is not doing what you think it is. Instead of using malloc
to allocate on the heap and since there is no free
(which will lead to a memory leak), it will be much easier if we allocate on the stack with a predetermined buffer size: char addrr[BUFFER_LENGTH]
. With BUFFER_LENGTH
defined before Station
's declaration as const int BUFFER_LENGTH = 20;
or some other appropriate length.
既然你说你不能使用std::string
,这将变得更加困难。这条线addrr = (char *)(malloc(sizeof(addrr+1)));
没有做你认为的那样。代替使用malloc
分配在堆上并因为没有free
(这将导致内存泄漏),这将是容易得多,如果我们分配堆栈上以预定的缓冲区的大小:char addrr[BUFFER_LENGTH]
。与BUFFER_LENGTH
定义 beforeStation
的声明为const int BUFFER_LENGTH = 20;
或其他一些适当的长度。
To use the non-default constructor, adding stations[i] = Station(c, addrr, mes);
at the end of the for loop will do the trick.
要使用非默认构造函数,stations[i] = Station(c, addrr, mes);
在 for 循环末尾添加即可。
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);
}
But, this is not going to work properly since the constructor is copying the addrr
pointer, not the data. I would recommend also changing the data member char *address
to char address[BUFFER_LENGTH]
. Then, in the constructor you can replace the line address=ad;
with strcpy(address, ad);
.
但是,这不会正常工作,因为构造函数正在复制addrr
指针,而不是数据。我还建议将数据成员更改char *address
为char address[BUFFER_LENGTH]
. 然后,在构造函数中,您可以address=ad;
用strcpy(address, ad);
.
Note: setAddress
and getAddress
will now need to be updated.
注:setAddress
和getAddress
现在需要更新。
Another line that is troubling is Station stations[size];
. This is non-standard since size
is not a known at compile time. Either use Station *stations= new Station[size];
and remember to delete
or if you can use a std::vector
, use std::vector<Station> stations(size);
另一条令人不安的线路是Station stations[size];
. 这是非标准的,因为size
在编译时是未知的。使用Station *stations= new Station[size];
并记住,delete
或者如果您可以使用 a std::vector
,请使用std::vector<Station> stations(size);
If you do go the std::vector
route, using push_back
will work nicely:
如果你确实走这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) );
}