我最近開始在Cpp編程,遇到了一個我無法解決的問題,也沒有找到自己的答案。C++函數不會改變我的參數
我,米感興趣爲什麼,當我傳遞和函數參數(fillInArray函數) 它不會改變任何東西。在調試器中,我發現vectorArray(我想傳遞的參數)根本不會改變,但是在這個函數裏的向量回推方法似乎可行,它會增加向量大小。 任何幫助將不勝感激,因爲這個問題否認我繼續這個程序。
header.h
#pragma once
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class header
{
private:
int numberOfBytes = NULL;
int number;
int argument;
vector<int> vectorArray;
//std::vector<int> vector2;
//std::vector<int> vector3;
public:
header();
~header();
void setBytes(int bytes);
int getBytes();
void askForBytes();
void fillInArray(vector<int> someVector);
void showArray();
void negateBytes();
void menu();
void addArrays();
void substractArray();
};
header.cpp
#include "header.h"
header::header()
{
askForBytes();
setBytes(number);
fillInArray(vectorArray);
//fillInArray(vector2);
showArray();
negateBytes();
showArray();
}
header::~header()
{
}
void header::setBytes(int bytes)
{
if (bytes % 8 == 0)
{
numberOfBytes = bytes;
cout << "You typed in: " << numberOfBytes << " bytes\n";
}
else
cout << "Wrong argument, number of bytes set to: " <<
numberOfBytes << " bytes" << endl;
}
void header::askForBytes()
{
cout << "Plz type in how many bytes: " << endl;
cin >> number;
}
int header::getBytes()
{
return numberOfBytes;
}
void header::fillInArray(vector<int> vector)
{
for (int i = 0; i < numberOfBytes; i++)
{
vector.push_back(rand() % 2);
}
}
void header::showArray()
{
for (unsigned int i = 0; i < vectorArray.size(); i++)
{
cout << vectorArray[i] << " ";
}
cout << endl;
}
void header::negateBytes()
{
for (int i = 0; i < numberOfBytes; i++)
{
if (vectorArray[i] == 0)
vectorArray[i] = 1;
else
vectorArray[i] = 0;
}
}
/*void header::menu()
{
cout << "Type argument to do stuff: " << endl <<
"1 to negate single vector\n 2 to add two vectors\n 3 to minus two vectors\n";
cin >> argument;
switch (argument)
{
case 1: negateBytes();
showArray(vector);
break;
case 2: addArrays();
showArray(vector);
break;
case 3: substractArray();
showArray(vector);
break;
default: cout << "Wrong argument";
}
}*/
void header::addArrays()
{
for (int i = 0; i < getBytes(); i++)
{
//if ((vector[i] && vector2[i]) == 1)
// vector3.push_back(0);
// else if ((vector[i] == 1 && vector2[i] == 0) || (vector[i] == 0 && vector2[i] == 1))
// vector3.push_back(1);
// else vector3.push_back(0);
}
}
void header::substractArray()
{
}
zadanie1.cpp = main.cpp中
#include "header.h"
void showText()
{
cout << "text";
}
int main()
{
header head;
system("Pause");
return 0;
}
我也談到了一些變量和函數,我將在稍後建立。 在此先感謝!
使用參考參數'void fillInArray(vector&someVector);' –
2014-10-18 17:06:14
每次使用'fillInArray'時,您正在填充'vector'的副本。這就是爲什麼你應該通過引用傳遞它。 – wowofbob 2014-10-18 17:08:53
非常感謝,它爲我工作! – TheGalax 2014-10-18 17:13:37