访问另一个函数的变量
Getting access to another function's variables
我有以下代码:
#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,或者实现你自己的动态数组类,并通过引用传递)。
相关文章:
- 是否可以将变量/函数返回作为模板参数传递
- 是否有一种方法可以修复编译器未找到特定的OPENCV变量/函数
- 访问实例化类的变量/函数
- 如何在变量函数参数列表中检测给定类型的参数的可用性,并在处理完所有参数后采取行动
- C 多组变量函数参数
- 最有cpu效率的方法是使用std::算法和变量函数模板的参数
- 在此作用域中未声明条件变量函数
- C 关于将数组复制到向量并调用其变量 /函数
- 仅在C 中的一个变量上,两个变量函数的数值集成(使用数值配方库)
- 在应用变量函数的矩阵元素上循环
- 如何向调试器隐藏变量/函数名
- C++11变量函数类型模板参数
- 变量函数参数的奇怪问题
- C++变量函数和cout
- c++模板变量函数未定义引用
- 我可以使用枚举类值作为变量函数的参数吗?
- 从另一个类访问变量/函数
- <"变量/函数"的多重定义>
- 从c++到C文件中定义的变量/函数的未定义引用
- 为什么转换变量函数参数很重要?