访问另一个函数的变量

Getting access to another function's variables

本文关键字:变量 函数 另一个 访问      更新时间:2023-10-16

我有以下代码:

#include <iostream>
#include "note.h";
using namespace std;
void prompt() {
    string opt;
    system("CLS");
    cout << "What do you want to do?" << endl << "1. Browse" << endl << "2. Add" << endl;
    cin >> opt;
    if(opt=="1") {
        cout << "Not yet.";
    } else if(opt=="2") {
        system("CLS");
        string title;
        string content;
        cout << "Title:" << endl;
        cin >> title;
        cout << "Content:" << endl;
        cin >> content;
        Note note(title, content);      
    } else {
        prompt();
    }
}
int main() {    
    int size = 0;
    Note* tNote = new Note[size];
    delete [] tNote;
    prompt();
    system("PAUSE");
    return 0;
}

我的问题是,如何在prompt()函数中向tNote添加另一个Note,并增加main()中定义的大小
目前我想做尺寸++;在prompt()中,我得到了"未定义的标识符"

最简单&优雅的方法是使用std::vector,并通过引用函数prompt()将其作为参数传递。

一旦您使用vector,您就不必像现在面临的那样为内存分配而烦恼,vector的大小会自动增长以适应您的对象。

既然这是家庭作业,我就不给你举一个代码示例了
阅读C++中的std::vector和通过引用传递参数,你应该能够解决你的家庭作业。

由于不能使用vector,您只需要将数组的大小保持在主函数之外的全局变量中。只需将"int size=0"行移到主函数上方,就可以从其他地方访问它。

请注意:作为一种设计实践,这是非常糟糕的,但它将解决您眼前的问题,并让您继续学习。如果你是老师,他们会解释有更好的方法来实现这一点(即使用STL,或者实现你自己的动态数组类,并通过引用传递)。