繁体   English   中英

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

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

Fox类中,我需要构建一个函数并返回一个字符串。 假设Fox* fox = new Fox(); 要求是:

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

thing1 !=thing2

那么我该如何实现呢?

我在下面尝试了代码,但有一些错误: 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";
        }
};

多亏了bwtrent,我认为您是对的。 我在上面修改了我的代码,并'foxWords' was not declared in this scope错误'foxWords' was not declared in this scope因为string say()函数是从虚函数派生的? Fox的父函数中的say函数必须虚拟化。

您朝着正确的方向前进,但是,应将元素推到构造函数中的向量中。 创建您的构造函数,推送相同的元素,您应该会做得很好。

您不能像当前那样推送项目,它必须在函数(可能是构造函数)内部完成。

如果唯一的目标是返回不同的字符串,则不需要向量。 就像是:

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

将确保大量呼叫使用唯一的字符串。 或者您可以使用rand()

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

可以使用无数种变体。

暂无
暂无

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

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