问题
Im writing a class within c++, however I am not certain on how to create the setters and getters for the arrays (sorry for it being a basic question!) I am getting the following error:
expected primary expression before ']' token
Here is my code:
Class planet: public body
{
private:
string name[];
string star[];
public:
void nameSetter (string h_name[])
{
name[] = h_name[];
}
};
Once again I am sorry for such I silly question, I know I am not passing an index through, however, when I create an index it throws up a large amount of errors!
回答1:
string name[];
This is not an array, it is a pointer. Use vectors
instead:
#include <vector>
class planet: public body
{
private:
vector<string> name;
vector<string> star;
public:
void nameSetter (const vector<string> &h_name)
{
name = h_name;
}
};
回答2:
Arrays in C++ have compile-time fixed sizes. You can't have a declaration like string name[];
because it leaves the size empty. You can't do that unless you provide an initialization list from which the size is determined.
In addition, array type arguments are transformed to pointer arguments. So your string h_name[]
argument is actually a string* h_name
.
name[] = h_name[];
This line doesn't make much sense. It's almost like you're trying to access elements of name
and h_name
without giving an index. Perhaps you were intending to assign the h_name
array to the name
array, like so:
name = h_name;
However, as we've just seen, h_name
is actually a pointer. And in fact, you can't assign to an array anyway, so even if h_name
were an array, this still wouldn't work.
You'll be much better off using a standard container like std::vector
. It appears that you want dynamically sized arrays anyway, so this will make that easy.
回答3:
Even though an answer has been selected, I think maybe the original question may have been misunderstood.
I think what the OP intended was that each instance of planet should have 1 name and 1 star; so the array notation he's used in his code is a misunderstanding on his part about arrays and strings. Based on this assumption I will continue.
When you declare
string name[];
I believe you just want to hold the name of 1 planet, in which case you don't need and array, you just need a single string. ie
string name;
The same goes for star.
This would make the code
Class planet: public body
{
private:
string name;
string star;
public:
void nameSetter (const string& h_name)
{
name = h_name;
}
};
来源:https://stackoverflow.com/questions/16374258/how-do-i-write-setters-and-getters-for-an-array-c