无法保存到Class中的变量?

时间:2018-11-30 10:36:15

标签: c++

入门代码。编译正常。 SetMemo似乎可以正常工作(它会重复输入),但是当我尝试使用ReadMemo时,savedmemo似乎为NULL。除此以外,将打印该行中包含的所有其他内容。我究竟做错了什么?我是否在其他地方意外擦除了变量?

#include "pch.h"
#include <iostream>
#include <string>
using namespace std;
int firstboot = 1;

class MEMOCLASS {
    public:
    void SetMemo(string memoinput_pvt) {
        savedmemo = memoinput_pvt;
        cout << savedmemo << " saved as a memo!" << endl;
        };
    string ReadMemo(){
        return savedmemo;
    };
    private:
    string savedmemo;
};

int main()
{
    MEMOCLASS MMObj;
    string input;
    string memoinputmain;
    if (firstboot == 1) {
        cout << "Hello! Please use \"write memo\" to store a memo or \"read memo\" to read a previously stored memo. Type \"exit\" to quit the programme." << endl;
        firstboot = 0;
    }
    else {
        cout << "Ok, anything else I can do for you?" << endl;
    }
    getline(cin, input);
    if (input == "write memo") {
        cout << "Ok, go ahead. Press Enter to record the Memo.\n";
        getline(cin, memoinputmain);
        MMObj.SetMemo(memoinputmain);
        main();
    }
    else if (input == "read memo") {
    cout << "The memo reads: " << MMObj.ReadMemo() << endl;
    main();
    }
    else if (input == "exit")
    {
        cout << "Cya!\n";
        return 0;

    }
    else if (input == "help")
    {
        cout << "Use \"write memo\" to store a memo or \"read memo\" to read a previously stored memo. Type \"exit\" to quit the programme.\n";
        main();
    }
    else {
        cout << "Invalid input!\n";
        main();
    }
}

2 个答案:

答案 0 :(得分:6)

两个问题:

  1. 在C ++中,您不允许递归调用the main function。请改用循环。 (无论从何处,以任何方式调用main都在您的代码中正式称为undefined behavior。)

  2. 由于您递归调用main,因此每次调用都会导致创建 new 并创建不同的变量MMObj

答案 1 :(得分:1)

首先要牢记一点。您不应致电main

现在,当您调用main时,您创建的对象将不复存在。 任何类似的代码

void foo()
{
    int x = 6;
    if (x == 6)
    {
        x = 7;
    }
    foo();
}

将在再次调用时创建一个新的x,为x赋予值6。

您可以传入对象以保持它们周围。

void foo(int x)
{
    if (x == 6)
    {
        x = 7;
    }
    foo(x);
}

根据您的情况,新建一个功能,例如runMMObj

MEMOCLASS runMMObj(MEMOCLASS MMObj) //you know this is a copy, right?
{
    //do reads and writes here
    return MMObj;
}

int main()
{
    MEMOCLASS MMObj;
    MMObj = runMMObj(MMObj);
    //rerun your new function if you want
}