简体   繁体   English

如何使函数在不同时间调用时返回不同的字符串? C ++

[英]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. Fox类中,我需要构建一个函数并返回一个字符串。 And let's say Fox* fox = new Fox(); 假设Fox* fox = new Fox(); The requirement is : 要求是:

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

and thing1 !=thing2 thing1 !=thing2

So how can I achieve this? 那么我该如何实现呢?

I tried codes below but it has some error: error: 'foxWords' does not name a type 我在下面尝试了代码,但有一些错误: 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. 多亏了bwtrent,我认为您是对的。 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? 我在上面修改了我的代码,并'foxWords' was not declared in this scope错误'foxWords' was not declared in this scope因为string say()函数是从虚函数派生的? The say function in Fox's parent function has to be made virtual. Fox的父函数中的say函数必须虚拟化。

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() ? 或者您可以使用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. 可以使用无数种变体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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