What does this mean? C++ basic programming

时间:2018-02-03 07:43:38

标签: c++

[Warning] non-static data member initializers only available with -std=c++11 or -std=gnu++11 [enabled by default]

error on a class private declaration it was on the int oddnumbers line

class odd
{
private:
    int oddnumbers[30], oddsum=0;
    char yes = 'y';
public:
    int oddnum()
    {   
        for(int i; i<30; i++)
            {

                cout<<"Enter odd number #"<<i+1<<": ";
                cin>>oddnumbers[i];
                oddsum=oddsum + oddnumbers[i];
                if(oddnumbers[i]%2 == 0 || oddnumbers == 0 )
                    {   

                        break;
                    }
                cout<<"Do you still want to enter a number(Y/N): ";
                cin>>yes;
                if(yes == 'n'|| yes == 'N')
                {
                    break;
                }
            }
        cout<<"Sum is: "<<oddsum<<"\n";
        if(oddnumbers[29] > 0)
        {
        cout<<"\nGoodjob!";
        }
    }
};

1 个答案:

答案 0 :(得分:0)

oddsum and yes are non-static data members (and oddnumbers too). The usual place to initialize non-static data members is in the class constructor. So you could rewrite your class like this

class odd
{
private:
    int oddnumbers[30], oddsum;
    char yes;
public:
    odd() // constructor
    {
        oddsum = 0;
        yes = 'y';
    }
    int oddnum()
    {
        ...
    }
};

But a better way would be to realise that all these data members are only used in the method oddnum and therefore you should change them to local variables, like this

class odd
{
public:
    int oddnum()
    {   
        int oddnumbers[30], oddsum=0;
        char yes = 'y';
        ...
    }
};

But once you have done that you can see that you have a class with no data members and only one method. Such a class doesn't really serve any purpose and you should convert it's method to a global function.

int oddnum()
{   
    int oddnumbers[30], oddsum=0;
    char yes = 'y';
    ...
}

In this code you are using classes inappropriately. A good C++ book will teach you when to use classes.