Reputation: 994
I am trying to find a way to define an array of unknown size in a class and "fill it in" using a constructor. Here is a simple example to give you a rough idea of what I am trying to do:
#include <iostream>
#include <vector>
using namespace std;
class MyClass{
public:
string Name;
double x[];
double y[];
MyClass(string aName, double aX, double aY){
Name=aName;
x[]=aX;
y[]=aY;
}
};
int main() {
MyClass object1("Object1",{1.0,2.0,3.0},{4.0,5.0,6.0});
}
Obviously, there are plenty errors, so I do not know where to start and how to achieve my goal!
Any guidance is appreciated.
EDIT
Here is a working solution based on the answers to this question. Thanks everyone!
#include <iostream>
#include <vector>
using namespace std;
class MyClass{
public:
string Name;
vector<double> x;
vector<double> y;
MyClass(string aName, vector<double> aX, vector<double> aY){
Name=aName;
x=aX;
y=aY;
}
};
int main() {
MyClass object1("Object1",{1.0,2.0,3.0},{4.0,5.0,6.0});
cout<<object1.Name<<endl;
cout<<object1.x[1]<<endl;
cout<<object1.y[2]<<endl;
}
Upvotes: 2
Views: 243
Reputation: 234715
Variable length arrays are not supported in standard C++.
In your case std::vector<double> x;
&c. are virtually drop-in replacements, and certainly are if you were to write
MyClass object1{"Object1",{1.0,2.0,3.0},{4.0,5.0,6.0}};
instead, noting that this will not call your constructor, which you are free to remove rather than attempting to fix the compilation errors.
Upvotes: 10
Reputation: 238351
An array of indeterminate size is an incomplete type. There can not be variables of incomplete type. Thus, your member variables are ill formed. Array variables, members included, must have a compile time constant size.
If you need arrays of runtime size, you need to allocate it dynamically. Simplest solution is to use std::vector
.
Upvotes: 5