簡體   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