繁体   English   中英

c ++构造函数的默认参数

[英]c++ constructor default parameters

如何编写指定默认参数值的构造函数,

#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;
    }
};

然后使用它只传递一些值而不考虑他们的订单?

例如:这有效:

char tmp;
foo f( &tmp );

但这不是:

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]

很快,你不能忽视订单。

但是你可以创建多个构造函数。

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) {}
};

编辑:

顺便说一下,使订单变量/可忽略不是一个好主意。 这有时会导致模糊或意外行为,这很难找到/调试。 在我的示例中使用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_;
};

就像提示一样,使用明确定义的构造函数/函数重载。

有一个命名参数成语。 它允许通过指定名称以任何顺序传递参数。 它还允许使用默认值保留一些参数,并在单个语句中仅设置选定的参数。 用法示例:

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

有关成语描述和File实现的详细信息,请访问http://www.parashift.com/c++-faq/named-parameter-idiom.html

C ++中没有办法忽略参数顺序。 您仍然可以使用函数重载和委托构造函数:

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以避免使用构造函数进行隐式转换。

订单是必要的,基于订单和数据类型函数重载正在工作...你可以重载函数来实现你需要的,就像

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)
    {
    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM