【问题标题】:Referencing and Changing global variables from classes using pointers使用指针从类中引用和更改全局变量
【发布时间】:2019-05-08 18:43:31
【问题描述】:

这是我们不久前在机器人俱乐部所做的练习。我们应该创建类,一个将用户输入分配给变量(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++ 知识的人可以帮助我理解我的代码有什么问题吗?谢谢!

【问题讨论】:

  • 这里有很多错误的地方,很难决定从哪里开始。内存泄漏。由于临时对象的地址而导致的未定义行为。这里肯定有一个非常基本的误解 C++ 是如何工作的。对你来说最好的事情是花一些时间reading a good C++ book。这里不仅有一个问题,而且有几个问题。哦,这里没有“全局变量”;所以还有一个术语问题。
  • 预期结果是什么?那o.inputText应该有用户输入的内容吧?
  • 致 Sam - 我知道我的代码写得不好,因为我是 C++ 新手。这就是我问这个问题的原因——因为我不知道为什么我的代码不起作用,而且互联网资源对我没有帮助。
  • 致金斯利 - 是的,这就是我想要的。

标签: c++ string class pointers iostream


【解决方案1】:

代码未正确创建 i 和 o 对象。我想你可以说Input *i = new Input(userInput); - 这会起作用,但也需要进一步的改变。

我更改了您的 Input::userInput() 以获取指向字符串的指针。这种指向参数的相同类型的布局适用于修改基本类型和对象。

我真的不喜欢使用cin 和cout,我个人会使用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 似乎是多余的,但我还是尝试使用它。

【讨论】:

    猜你喜欢
    • 2014-01-27
    • 1970-01-01
    • 2014-01-23
    • 2021-11-11
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2014-05-18
    • 1970-01-01
    相关资源
    最近更新 更多