【发布时间】:2014-07-09 22:36:57
【问题描述】:
如何编写指定默认参数值的构造函数,
#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]
【问题讨论】:
标签: c++ c++11 parameters constructor default-value