C ++ constructor default options

How to write a constructor that defines default parameter values,

#include <iostream>

using namespace std;

struct foo
{
    char *_p;
    int   _q;

    foo( char *p = nullptr, int q = 0 ): _p(p), _q(q)
    {
        cout << "_q: " << _q << endl;
    }
};

and then use it, passing only some values ​​without regard to their order?

For example: this works:

char tmp;
foo f( &tmp );

but this is not so:

foo f( 1 );

$ g++ -O0 -g -Wall -std=c++0x -o test test.cpp
test.cpp: In function β€˜int main(int, char**)’:
test.cpp:18:11: error: invalid conversion from β€˜int’ to β€˜char*’ [-fpermissive]
test.cpp:10:2: error:   initializing argument 1 of β€˜foo::foo(char*, int)’ [-fpermissive]
+4
source share
4 answers

In short, you cannot ignore order.

However, you can create more than one constructor.

struct foo
{
    char *_p;
    int   _q;

    foo( char *p, int q): _p(p), _q(q) {}
    foo( char *p): _p(p), _q(0) {}
    foo( int q): _p(nullptr), _q(q) {}
};

Edit:

, /. , /. NULL , :

class foo {
public:
    foo(int x, unsigned char y=0) : x_(x), y_(y) {}
    foo(unsigned char x, int y=0) : x_(y), y_(x) {}

    int  x_;
    char y_;
};

/.

+2

. , . . :

File f = OpenFile("foo.txt")
       .readonly()
       .createIfNotExist()
       .appendWhenWriting()
       .blockSize(1024)
       .unbuffered()
       .exclusiveAccess();

File http://www.parashift.com/c++-faq/named-parameter-idiom.html

+2

++ . , :

struct foo {
    char *_p;
    int   _q;
    // this is the default constructor and can also be used for conversion
    foo( char *p = nullptr, int q = 0 ): _p(p), _q(q)
    {
        cout << "_q: " << _q << endl;
    }
    // this constructor canbe used for conversion.
    foo( int q, char *p = nullptr): foo(p, q) {}
};

, explicit, .

+1

, , ... ,

struct foo
{
    char *_p;
    int   _q;

    foo( char *p, int q): _p(p), _q(q) {}
    foo( int q, char *p): _p(p), _q(q) {}
    foo( char *p):foo(p,0)
    {  
    }
    foo( int q):foo(q,nullptr)
    {
    }
};
0

Source: https://habr.com/ru/post/1541407/


All Articles