c++将函数传入主函数错误
c++ passing function into main error
嗨,我有以下c++代码,我想调用函数到main,以下是我的代码:
#include <iostream>
#include <numeric>
int main()
{
using namespace std;
readData();
int sumA = accumulate(A, A + sizeof(A) / sizeof(int), 0);
int sumB = accumulate(B, B + sizeof(B) / sizeof(int), 0);
cout << ((sumA > sumB) ? "Array A Greater Than Array Bn" : "Array B Greater Than Array An");
return 0;
}
void readData()
{
int A[] = { 1, 1, 8};
int B[] = { 2, 2, 2};
}
我有以下错误的cli:
test.cpp:3:7: error: storage size of ‘B’ isn’t known
test.cpp:4:7: error: storage size of ‘A’ isn’t known
我错在哪里?由于
变量A
和B
是函数readData
的局部变量,不能被其他函数访问。
将它们声明为全局变量(不推荐)或main
中的局部变量,并将它们作为参数传递给readData
函数。
我还建议您使用std::vector
而不是普通数组。
首先,要小心C和c++中数组的大小。阅读这里获取更多信息:http://www.cplusplus.com/faq/sequences/arrays/sizeof-array/
但是要像这样使用std::vector。
#include <iostream>
#include <vector>
#include <numeric>
typedef std::vector<int> int_vec_t;
//Call by reference to set variables in function
void readData(int_vec_t& v1, int_vec_t& v2)
{
v1 = int_vec_t{1,1,8}; //This only works for C++11
v2 = int_vec_t{2,2,2};
}
void readUserData(int_vec_t& v)
{
for(;;)
{
int val;
std::cin>>val;
if(val == 0) break;
v.push_back(val);
}
}
int main()
{
using namespace std;
int_vec_t A;
int_vec_t B;
readData(A,B);
//Or
readUserData(A);
readUserData(B);
int sumA = accumulate(A.begin(), A.end(), 0); //Then use iterators
int sumB = accumulate(B.begin(), B.end(), 0);
cout << ((sumA > sumB) ? "Array A Greater Than Array Bn" : "Array B Greater Than Array An");
return 0;
}
相关文章:
- "error: no matching function for call to"构造函数错误
- 为什么类中的ostringstream类型的成员会导致";调用隐含删除复制构造函数";错误
- 尝试将unique_ptrs推送到向量时使用纯虚拟函数错误
- C++ OpenCV 卡尔曼滤波器构造函数错误
- C++:用户定义的显式类型转换函数错误
- C++ 合并字符串以'system'函数错误
- C++ wmain 函数错误时使用 Unicode
- 结构数组的构造函数错误,错误消息:没有构造函数实例与参数列表匹配
- C++ 中常量属性的初始化构造函数错误
- 线程 std::调用未知类型,无法专门化函数错误
- 表单显示对话框函数错误,并且不执行下面的语句
- 函数错误 C2059:语法错误:'>'不起作用
- STL向量上出现奇怪的复制构造函数错误
- C++ Visual Studio 重载函数错误:没有重载函数的实例与指定的类型匹配
- C++引用已删除函数错误
- 为什么通过带有文字编号的引用调用会出现"无匹配函数"错误?
- C++ 乘法定义的构造函数错误消息似乎错误
- 在 c++ 代码中将数组传递给函数错误
- FFMPEG avcodec_decode_video2函数错误代码
- 为什么我会收到转换函数错误