lundi 26 janvier 2015

Setting Default Parameters in C++


I have a little question about how default values are given to function parameters in C++. The problem I faced is probably due to my lack of understanding as to where the parameters are supposed to be declared/defined in the function prototype or the function header, or both? Codes are below with the errors noted:



#include <iostream>

using namespace std;

float volume(float l, float w, float h);

int main() {

float length;
float width;
float height;

cout << volume() << endl; // Here, with 'volume()' underlined, it says:
//no matching function for call to 'volume()'

cout << "Length: ";
cin >> length;

cout << "Width: ";
cin >> width;

cout << "Height: ";
cin >> height;

cout << "Volume = " << volume(length, width, height) << endl;


}

float volume(float l = 1, float w = 1, float h = 1){

float vol = l * w * h;

return vol;
}


In another attempt, here's what happened:



#include <iostream>

using namespace std;

float volume(float l = 1, float w = 1, float h = 1);

int main() {

float length;
float width;
float height;

cout << volume() << endl;

cout << "Length: ";
cin >> length;

cout << "Width: ";
cin >> width;

cout << "Height: ";
cin >> height;

cout << "Volume = " << volume(length, width, height) << endl;


}

float volume(float l = 1, float w = 1, float h = 1){ //Here, Xcode says that
// that the error is: Redefinition of default argument. < which I believe I understand.

float vol = l * w * h;

return vol;
}


In my last attempt, which is the one that worked, I did this:



#include <iostream>

using namespace std;

float volume(float l = 1, float w = 1, float h = 1);

int main() {

float length;
float width;
float height;

cout << volume() << endl;

cout << "Length: ";
cin >> length;

cout << "Width: ";
cin >> width;

cout << "Height: ";
cin >> height;

cout << "Volume = " << volume(length, width, height) << endl;


}

float volume(float l, float w, float h){

float vol = l * w * h;

return vol;
}


Could someone please explain to me the logic behind why the latter worked while the first two did not? Is there another way that the code would still work in the same way with the parameters specified elsewhere or the default values set in some place else? Are there any conventions or more favored practices in this area?


Adam





Aucun commentaire:

Enregistrer un commentaire