eswaat eswaat - 3 months ago 27
C++ Question

error: expected identifier before string constant or error: 'perf' is not a type

I am getting below error, I tried this 2 ways but didn't solve it.

Below is the code

class Stat_S{
public:
Stat_S(const char *name) :
{
........
}

~Stat_S();
};


struct temp {
Stat_S sp("ppin");
}


error: expected identifier before string constant

class Stat_S{
public:
Stat_S(const char *name) :
{
........
}

~Stat_S();
};

const char *temp="ppin";
struct temp {
Stat_S sp(temp);
}


error: 'temp' is not a type

class Stat_S{
public:
Stat_S(const char *name) :
{
........
}

~Stat_S();
};

struct temp {
Stat_S*sp = new Stat_S("ppin");
}


work's fine no error

main()
{
static temp2 *temp;
temp2 = new temp[2];
}


How to solve 1st or 2nd case ? I want to call the constructor of Stat_S from struct temp. I don't wont to use 3rd case, because I already have big definition that uses dot (.) for sp I don't want to change it to -> after using instance.

Answer

In-class initialization of non-static members can be performed using brace or equal initializers. The 3rd case is an instance of using equal. To do the 1st or 2nd correctly, use braces like this :

struct temp {
         Stat_S sp{"ppin"};
    }