首页 > 解决方案 > 用另一个函数(在类中)调用一个函数时出现问题。没有错误代码 C++

问题描述

class DatingSim
{
public:
    string userName;
    int userAge;
    int day1Place;
    string places[4] = { "Coffee Shop", " Duck Pond", "Club" , "Class"};
    string dayOneA = "W E L C O M E  T O  D A T I N G  G A M E";


    void slowPrint(string str, int time)
    {
        for (size_t i = 0; i != str.size(); ++i) 
        {
            cout << str[i];
            Sleep(time);
        }
    }
    void dayOne();

void DatingSim::dayOne()
{

    slowPrint(dayOneA, 250);
    cout << endl;

... other code (just cout stuff shouldn't be a problem)
}

int main()
{
    DatingSim NEWGAME;
    NEWGAME.dayOne();

    return 0;
}

因此,以前我使用的是字符串数组,而不是用于 slowprint 函数参数的字符串,但它不起作用,所以我只切换到字符串,但它不起作用。我对它进行了测试,当它不在一个班级内时它可以工作。我不应该使用课程吗?我正在创建一个小游戏,我宁愿能够使用一个类。当我尝试运行时,没有错误消息只是说 FAILED。

标签: c++functionclassvoidcout

解决方案


正如建议的那样,您需要在每个字母之后刷新输出流,否则您会看到最后打印出整个字符串。

#include <chrono>
#include <iostream>
#include <string>
#include <thread>

using namespace std;

class DatingSim {
public:
    string userName;
    int userAge;
    int day1Place;
    string places[4] = { "Coffee Shop", " Duck Pond", "Club" , "Class"};
    string dayOneA = "W E L C O M E  T O  D A T I N G  G A M E";

    void slowPrint(string str, int time)
    {
        for (size_t i = 0; i != str.size(); ++i) 
        {
            cout << str[i] << flush;
            this_thread::sleep_for(chrono::milliseconds(time));
        }
    }

    void dayOne()
    {
        slowPrint(dayOneA, 250);
        cout << endl;
    }
};

int main()
{
    DatingSim NEWGAME;
    NEWGAME.dayOne();
    return 0;
}

推荐阅读