天天看點

C++ 之 explicit,mutable,volatile 淺析

explicit:放在構造函數前面可以阻止構造函數的隐式類型轉換。這樣可以避免不必要的錯誤。

代碼用例:

public static explicit operator RMB(float f)
{
	uint yuan = (uint)f;
	uint jiao = (uint)((f - yuan) * 10);
	uint fen = (uint)(((f - yuan) * 100) % 10);
	return new RMB(yuan, jiao, fen);
}
           

mutable:類的const成員函數本來不可以改變類的成員變量的值,但是一旦某個成員變量被mutable修飾,那麼const成員函數可以改變它。

代碼用例:

#include <iostream>
using namespace std;
class Foo {
public:
    void set_bar(int val)
    {
        bar = val;
    }
    void set_bar_const(int val) const
    {
        bar = val;
    }
private:
    mutable int bar;
};
 
int main(int argc, char *argv[])
{
    Foo foo;
    foo.set_bar(0);
    foo.set_bar_const(0);
 
    const Foo cfoo(foo);
    // cfoo.set_bar(0); 出錯
    cfoo.set_bar_const(0);
 
    return 0;
}
           

volatile:關鍵字是一種類型修飾符,用它聲明的類型變量表示可以被某些編譯器未知的因素更改,比如:作業系統、硬體或者其它線程等。遇到這個關鍵字聲明的變量,編譯器對通路該變量的代碼就不再進行優化,進而可以提供對特殊位址的穩定通路。

(擴充閱讀:http://blog.csdn.net/helonsy/article/details/7164655)

代碼用例:

volatile int i=10;
           

繼續閱讀