The default argument for a structure reference in C ++

I want to specify a default value for a function parameter, which is a reference to a structure. What can I specify as the default value?

+5
source share
5 answers

First decision:

If this is a link to a structure, you should make a link constand do this:

struct A
{
    //etc
    A(int, int);
};  

void f(int a, const A & = A(10,20) ) //const is necessary
{
    //etc
}

This is not so good for obvious reasons: it makes a parameter const(you may not want it), and your structure should have a constructor (you may not have one).

The second solution:

So, if you do not want to do this const, or if you do not want to have a constructor in the structure, you can do this:

struct Point
{
     int x, y, z;
};  

Point g_default_point = {10,20,30};
void g(int a, Point & p = g_default_point )
{
    //etc
}

Still not good. Defining a global variable is a great idea.


:

void g(int a, Point & p)
{
    //your code
}
void g(int a) //this function would behave as if you opt for default value!
{
     Point default_value = {10,20,30};
     g(a, default_value);
}

const, .

+15

++ 0x:

#include <iostream>

struct structure { int x, y ; } ;

int f(int a, structure &s = structure{10,20}) {
  return s.x + s.y ;
}

int main() {
  std::cout << f (99) << std::endl ;
}

, s const. . http://ideone.com/sikjf.

+3

.

. - . , .

, . 0 .

0

( ), . , .

:

struct X
{
    X operator+(const X&) const;
};

X x1;
X& x2;

void f(X& x = x1);
void f(X& x = x2);
void f(const X& x = x1 + x1);
0

, . int rowCount(const QModelIndex &parent = QModelIndex()) const; :

  • - , .

  • - , .

  • , , , , .

, , .

, , int test (int &i=int()); ( , VisualStudio 2008 error C2440: 'default argument' : cannot convert from 'int' to 'int &')

0

All Articles