I tried on a class member data error occurred while initializing.
System prompts an error message:error C2059: syntax error : '{'
error C2143: syntax error : missing ';' before '{'
error C2143: syntax error : missing ';' before '}'
My codes is as follows:
#include
using namespace std;
#define COURSE_NUM 4
class Student
{
public:
Student();
void ResetScore(int index,int new_score);
private:
float score[COURSE_NUM];
};
Student::Student(){
this->score[COURSE_NUM]={0.0}; // Attempting to initialize the array.
}
void Student::ResetScore(int index,int new_score)
{
this->score[index]=new_score;
}
int main()
{
Student stu;
stu.ResetScore(1,98.5);
return 1;
}
Thanks.

VulpesPosted Dec 9, 2013, 9:38 AM
If you change it to a float, then it will work fine.
2. The difference is that you're initializing the float array where it's defined.
Previously, you'd declared it as a data member of the Student class but were attempting to initialize it in the constructor but you can't use the {...} syntax for that.
Ken HPosted Dec 9, 2013, 7:50 PM
Ken HPosted Dec 8, 2013, 8:38 PM
But i have two questions:
1)
#include
using namespace std;
#define COURSE_NUM 4
class Student
{
public:
Student();
void ResetScore(int index,int new_score);
void print();
private:
float score[COURSE_NUM];
};
Student::Student(){
for(int i = 0; i < COURSE_NUM; i++) score[i]=000.0f;
}
void Student::ResetScore(int index,int new_score)
{
this->score[index]=new_score;
}
void Student::print()
{
int i;
for (i=0;i
int main()
{
Student stu;
stu.ResetScore(1,98.5);
stu.print();
return 1;
}
The result is:
0 98 0 0
I think the result should be:
0 98.5 0 0
2)
Why it can not accept this way to initialize an array?
However, in the following procedure by the same method is allowed.
#include
using namespace std;
#define COURSE_NUM 4
int main()
{
float test[COURSE_NUM]={0.0};
int i;
for(i=0;i
}
VulpesPosted Dec 8, 2013, 10:56 AM