简体   繁体   中英

How to make a function return different strings when called at different times? C++

In a class Fox , I need to build a function and return a string. And let's say Fox* fox = new Fox(); The requirement is :

    std::string thing1 = fox->say();
    std::string thing2 = fox->say();

and thing1 !=thing2

So how can I achieve this?

I tried codes below but it has some error: error: 'foxWords' does not name a type

class Fox : public Canid{
    public:
        Fox(){
            int a = 0;
            std::vector<string> foxWords;
            foxWords.push_back("words1");
            foxWords.push_back("words2");

        };  // constructor is needed 


        string say(){
            a+=1;
            return foxWords.at(a%2);
        }   
        string name(){
            return "fox";
        }
};

Thanks to bwtrent I think you are right. I revised my code above and it returns error 'foxWords' was not declared in this scope Is it because the string say() function was derived from a virtual function? The say function in Fox's parent function has to be made virtual.

You are headed in the right direction, however, you should push elements to your vector in your constructor. Create your constructor, push those same elements, and you should be good to go.

You cannot push items like you are currently, It must be done inside of a function(probably the constructor).

If the only goal is to return different strings, you don't need a vector. Something like:

class Fox
{
    int myState;
public:
    Fox() : myState( 0 ) {}
    std::string say()
    {
        ++ myState;
        std::ostringstream s;
        s << myState;
        return s.str();
    }
}

will ensure unique strings for a good number of calls. Or you can use rand() ?

std::string Fox::say()
{
    int size = rand() % 10 + 1;
    std::string results;
    while ( results.size() < size ) {
        results += "abcdefghijklmnopqrstuvwxyz"[rand() % 26];
    }
    return results;
}

There are an infinite number of variants which could be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM