I have a class of the following form:
class T
{
public:
/// Constructor
T(const std::string& baseName);
};
Now within the main() method I am trying to create an array of the objects of the class using:
T* s = new T[20](baseFileName);
I am not getting where I am making a mistake...can someone please help.
The error which I am getting is:
error: ISO C++ forbids initialization in array new [-fpermissive]
You should first create the array of objects like below:
T* s = new T[20]; //allocating 20 objects
now you can call your desired function by making a little change:
class T
{
public:
T(){};//default constructor
/// Constructor
SetValue(const std::string& baseName);
};
call the function using a loop:
for( int i=0 ; i<20;i++)
s[i].SetValue(baseString);
The compiler is telling you exactly what's wrong. You can't do this:
T* s = new T[20](baseFileName);
More specifically, you can't have that (baseFileName)
bit when you use new. Just add a default constructor to T and fill it in yourself. Maybe add a method to your T class that returns array for you without you having to loop every time you need to construct one.
T * s = new T[20];
for(int i = 0; i < 20; i++) { s[i].setName(baseFileName); }
Or since you already know what the array is going to look like at compile-time:
T s [20] {baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.