使用指针从类中引用和更改全局变量

时间:2018-12-07 01:35:29

标签: c++ string class pointers iostream

这是我们不久前在机器人俱乐部中所做的一种做法。我们应该为类创建一个类,该类将用户输入分配给变量(cin),另一类将其输出(cout)。我们需要使用指针来实现这一点,而这正是我想出的。

#include "stdafx.h"
#include <iostream>
#include <string>

using namespace std;

class Input
{
public:
    string* textString = new string();

    Input(string uInput)
    {
        textString = &uInput;
    }

    void userInput() {
        cout << "Enter some text - ";
        cin >> *textString;
    }
private:
    // Nothing yet
};


class Output
{
public:
    string* inputText = new string();

    Output(string uInput)
    {
        inputText = &uInput;
    }

    void userOutput() {
        cout << *inputText << endl;
    }
private:
    // Nothing yet
};

int main()
{
    string userInput = "EMPTY";
    cout << &userInput << endl;

    Input i = Input(userInput);
    i.userInput();

    Output o = Output(userInput);
    o.userOutput();

    return 0;
}

但是,它似乎不起作用。当我在Visual Studio 2018中运行此命令并输入一个值时,它会等待几秒钟并显示``按任意键继续...''并结束程序。编译器中也不显示任何内容。有更多C ++知识的人可以帮助我理解我的代码有什么问题吗?谢谢!

1 个答案:

答案 0 :(得分:1)

代码未正确创建io对象。我想您可能已经说过Input *i = new Input(userInput);-可以,但是也需要进一步的更改。

我将您的Input::userInput()更改为指向字符串的指针。指针到参数的布局同样适用于修改基本类型和对象。

真的不喜欢使用cincout,我个人会使用fgets(),然后将其中的值放入您的字符串。

#include <string>
#include <iostream>


class Input
{
    private:
    std::string textString;

    public:
    Input ( std::string uInput )
    {
        textString = uInput;
    }

    void userInput( std::string *intoString )
    {
        std::cout << "Enter some text - ";
        std::getline( std::cin, textString );
        *intoString = textString;
    }
};


class Output
{
    private:
    std::string inputText;

    public:
    Output( std::string uInput )
    {
        inputText = uInput;
    }

    void userOutput()
    {
        std::cout << inputText << std::endl;
    }
};

int main(  )
{
    std::string userInput = "EMPTY";
    std::cout << userInput << std::endl;

    Input i( userInput );
    i.userInput( &userInput );

    Output o( userInput );
    o.userOutput();

    return 0;
}

我不清楚Input对象应该如何工作。本地textString似乎很多余,但是我还是尝试使用它。