ARentalTV
ARentalTV

Reputation: 376

invalid use of non-static member

just started learning some cpp and got this stuff going:

#include <string>

using std::string;

class Vigenere{
    public:
        Vigenere(string key, string alphabet = "abcdefghijklmnopqrstuvwxyz");
        string encode(string message, string key = _key, string alphabet = _alphabet);
        string decode(string message, string key = _key, string alphabet = _alphabet);


    private:
        string _alphabet;
        string _key;
};

while trying to compile it says "10 [Error] invalid use of non-static data member 'Vigenere::_key'";

line 10 is string Key;

So, is there a way to make it so i can use those variables for each object separately while using them as default arguments?

Upvotes: 1

Views: 743

Answers (1)

4386427
4386427

Reputation: 44274

To my knowledge it is not directly possible.

But you can do:

class Vigenere{
    public:
        Vigenere(string key, string alphabet = "abcdefghijklmnopqrstuvwxyz");
        string decode(string message, string key, string alphabet);
        string decode(string message, string key)
        {
           return decode(message, key, _alphabet);
        }
        string decode(string message)
        {
           return decode(message, _key, _alphabet);
        }

        // and same for encode


    private:
        string _alphabet;
        string _key;
};

It takes more source code lines but should give the user of the class the same interface, i.e.

someVigenere.decode("myMessage");          // Use key, alphabet from the object instance
someVigenere.decode("myMessage", "myKey"); // Use alphabet from the object instance
someVigenere.decode("myMessage", "myKey", "myAlphabet"); // Pass all

Upvotes: 7

Related Questions