访问另一个函数的变量 [英] Getting access to another function's variables

查看:193
本文介绍了访问另一个函数的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  #include< iostream> 
#includenote.h;

using namespace std;

void prompt(){
string opt;
system(CLS);
cout<< 您想做什么? << endl<< 1.浏览<< endl<< 2.添加< endl;
cin>>选择;
if(opt ==1){
cout< 还没。;
} else if(opt ==2){
系统(CLS);
string title;
string content;
cout<< Title:<< endl;
cin>>标题;
cout<< Content:<< endl;
cin>>内容;
注释(标题,内容);

} else {
prompt();
}
}

int main(){
int size = 0;
Note * tNote = new Note [size];

delete [] tNote;
prompt();
system(PAUSE);
return 0;我的问题是 - 我如何添加另一个注意到tNote里面prompt()
}



<函数并增加它们在main()中定义的大小?

目前当我想要做size ++时;

解决方案

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



一旦你使用vector,你不必费心内存分配dilemnas像你现在面临的,矢量自动增长的大小,以适应你的对象。 / p>

因为,作业我不会给你一个代码示例。

阅读关于 std :: vector ,并在C ++中通过引用传递参数,你应该能够解决你的家庭作业。


I've got following code:

#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;
}

My question is - how can I add another Note to tNote inside prompt() function and increase their size defined in main()?
Currently when I want to do size++; inside prompt() I'm getting "undefined identifier".

解决方案

Simplest & elegant way is to use a std::vector and pass it as an argument by reference to function prompt().

Once you use vector, you don't have to bother about the memory allocations dilemnas like one you are facing now, vector automatically grows in size to accomodate your objects.

Since, it is homework I am not going to give you a code example.
Read about std::vector and passing arguments by reference in C++ and you should be able to solve your homework.

这篇关于访问另一个函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆