Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this say to 'Expected '('' to a integer in cost? [duplicate]

For example:

struct Spell 
{
    int id;
    vector<int> cost(4);
};

It says

'Expected parameter declaration'.

Also does this piece of code have a difference?

if (can(vector <int>inv, spell.cost)) 
{
    cout << "CAST " << spell.id << endl;
    done = true;
    break;
}

This one says

'Expected '(' for function-style cast or type construction'
        
        

Could by any chance lend me a hand?

like image 608
doogy Avatar asked Jan 24 '26 23:01

doogy


1 Answers

As mentioned in the member initialization section in cppreference.com:

Non - static data members may be initialized in one of two ways :

  1. In the member initializer list of the constructor.

    struct S
    {
        int n;
        std::string s;
        S() : n(7) {} // direct-initializes n, default-initializes s
    };
    
  2. Through a default member initializer, which is a brace or equals initializer included in the member declaration and is used if the member is omitted from the member initializer list of a constructor.

    struct S
    {
        int n = 7;
        std::string s{ 'a', 'b', 'c' };
        S() {} // default member initializer will copy-initialize n, 
               // list-initialize s
    };
    

As per the above (emphasis mine), your member declaration is wrong.

I assume that, your intention was to have a vector of ints (i.e cost) as member and allocate 4 integers and default (value)initialize them .

You can fix it by either of the following ways:

  1. uniform - braced initialization
    struct Spell {
        int id;
        std::vector<int> cost{ std::vector<int>(4) };
        //                  ^^^                  ^^^^
    };
    
  2. equals initializer
    struct Spell {
        int id;
        std::vector<int> cost =  std::vector<int>(4); // or decltype(cost)(4)
        //                   ^^^^^^^^^^^^^^^^^^^^^^^^
    };
    
  3. provide a constructor and in constructor member initializer
    struct Spell { 
        int id; 
        std::vector<int> cost;
        Spell()
            : cost(4) // constructor member initializer
        {} 
    };
    

Since std::vector has the std::initializer_list constructor, unfortunately you can not write std::vector<int> cost{ 4 }, as it will be interpreted, the 4 being a single vector element.

like image 137
JeJo Avatar answered Jan 26 '26 14:01

JeJo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!