如何编写指定默认参数值的构造函数
#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]
答案 0 :(得分:2)
很快,您无法忽略该订单。
但您可以创建多个构造函数。
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
参数调用会导致歧义或this之类的内容:
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_;
};
就像提示一样,使用明确定义的构造函数/函数重载。
答案 1 :(得分: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 :(得分:1)
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
以避免使用构造函数进行隐式转换。
答案 3 :(得分:0)
订单是必要的,基于订单和数据类型函数重载正在工作... 你可以重载函数来实现你所需要的,比如
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)
{
}
};