I want to new a StringArray as follow:
class Test
{
public:
QString* str[];
Test() {
str = new QString[];
}
};
is there some wrong: about str = new QString[] ?
You didn't specify a size for the array.
Note that there is special syntax for the delete operator when deleting an array as well:
QString* strings;
strings = new QString[10];
delete[] strings;
If you want a dynamic array, consider using STL vector (std::vector<QString> in this case) instead.
QString *arr = new QString[10] {"abc","def"}; Whether you can use that depends on your compiler.[] on the declaration would make strings a pointer to a pointer. The correct declaration would be QString* strings;.QString* str[];
Declares a array of the type QString*. If you need a single string, what you need is, simply:
QString* str;
str = new QString;
However, Usually You don't need to do allocate dynamic memory explicitly. QString would provide its own memory management.
If you need a collection of strings, You are much better off using an container class like vector.
QVector<QString> str;
QString* str[] declares an array of QString pointers. A pointer is more or less synonymous with an array. If you just want an array of QString's, you should do this:
QString* str;
Test() {
str = new QString[10];
}
This will make str point to an array of 10 QStrings. The [] in your declaration is incorrect unless you would want to make a 2D array. Of course, if you do this, make sure to remember to delete [] str; at some point to release your memory.
If the size of your array is known at compile time, you're better off not using any dynamic allocation at all:
QString str[10];
Test() { }
This code will work the exact same as it does above, but you can avoid dealing with the new and delete.
Or, as others have suggested, you can just use std::vector<QString> and let the STL deal with it.
class Test { QString str[] = {"USA", "CHINA"}; Test() { } }; isn't allowed by the C++ standard unless you're using C++11.You probably want QStringList
std::vector<QString>(or use one of Qt's collections).QStringListas a built-in typedef; I suggest looking into that.