-
December 14th, 2017, 07:48 AM
#1
Default values for a user-defined types
Hi all,
Please consider this snipped-code:
Code:
int main()
{
cout << int() << endl;
return 0;
}
This will usually result in showing 0 as the output.
Consider that we have a user-defined type like this:
Code:
class myvals
{
public:
myval() { };
int x = 5;
double y = 12.5;
};
Now consider a function that receives an int and a double as its arguments:
Code:
void foo(int i, double d) {
cout << "i = " << i <<" and d = " << d << endl;
}
Now how to use the function foo this way:
?
-
December 14th, 2017, 08:24 AM
#2
Re: Default values for a user-defined types
Perhaps you just need to do some function overloading:
Code:
void foo(int i, double d) {
cout << "i = " << i <<" and d = " << d << endl;
}
void foo(const myvals& vals) {
foo(vals.x, vals.y);
}
Now this will work as expected:
-
December 15th, 2017, 06:37 AM
#3
Re: Default values for a user-defined types
Another way is to instantiate the class's object and pass it to the function parameter.
Code:
#include <iostream>
#include <string>
class myvals
{
public:
myvals() : x(5), y(12.4) {}
int x;
double y;
};
void foo(int i, double d) {
std::cout << "i = " << i <<" and d = " << d << std::endl;
}
int main()
{
const myvals& ref = myvals();
foo(ref.x, ref.y);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|