2017-05-14 43 views
-5
#include<iostream> 

    using namespace std; 

    class A 
    { 

    public: 
    A(int x) 
    { 
    a=x; 
    } 

    int a; 
    }; 

    void fun(A temp) 
    { 
    cout<<temp.a<<endl; 
    } 

    int main() 
    { 
    fun(1); 
    } 

在這裏,我們傳遞的原始值,以有趣的方法,並使用A級 的 對象任何人都可以解釋我如何上面的代碼工作,並使用其中的理念抓?任何人都可以解釋我如何上面的代碼工作和使用哪個概念?

+4

這些都是很基本的概念,應該在任何好的[圖書]的第一章(覆蓋http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-列表) – user463035818

+0

你是什麼意思「哪個概念」? –

回答

0

我評論了你的代碼,並使它更清晰一些。 閱讀來自(1) - >(5)的評論。

#include <iostream> 

using namespace std; 

class A { 

public: 
    A(int x) // (3): gets called by f to initialize an object of class A with x=1 
    { 
     a = x; 
    } 

    int a; 
}; 

void fun(A temp) // (2): Assumes 1 is a type class A. But it hasn't yet been initialized. So it calls Constructor. (tmp = new A(1)) 
{ 
    // (4): Now temp is an object of class A 
    cout << temp.a << endl; // Prints temp.a 
    // (5): temp object is getting destroyed. 
} 

int main() 
{ 
    fun(1); // (1): Calls fun() with argument of 1 
} 
0

A類有一個構造函數,它接收一個整數作爲參數。

因此,傳遞給樂趣整數參數自動澆鑄到A.

在該自動澆鑄過程中,一個目的(所謂的氣溫)被創建,它的場的「A」與1

初始化
+0

感謝您的解釋,但是如果我們在A類中有多個數據成員,並且我們只傳遞1個值,那麼在投射過程中會發生什麼? – Nirav

+0

自動轉換將根據你如何定義你的構造函數來工作。 – drorco

相關問題