2012-04-09 280 views
1

我下週正在爲C++進行測試,並且正在爲它做好準備。我有兩個班,如下所示,我很困惑。我必須逐行執行代碼,並且對標記行(class two內部的x = ...y = ...)感到困惑 - 執行從哪裏開始?在另一個類中調用一個類的構造函數

#include <iostream> 
using namespace std; 

class one { 
    int n; 
    int m; 
    public: 
    one() { n = 5; m = 6; cout << "one one made\n"; } 
    one(int a, int b) { 
     n = a; 
     m = b; 
     cout << "made one one\n"; 
    } 
    friend ostream &operator<<(ostream &, one); 
}; 

ostream &operator<<(ostream &os, one a) { 
    return os << a.n << '/' << a.m << '=' << 
     (a.n/a.m) << '\n'; 
} 

class two { 
    one x; 
    one y; 
    public: 
    two() { cout << "one two made\n"; } 
    two(int a, int b, int c, int d) { 
     x = one(a, b); //here is my problem 
     y = one(c, d); //here is my problem 
     cout << "made one two\n"; 
    } 
    friend ostream &operator<<(ostream &, two); 
}; 

ostream &operator<<(ostream &os, two a) { 
    return os << a.x << a.y; 
} 

int main() { 
    two t1, t2(4, 2, 8, 3); 
    cout << t1 << t2; 
    one t3(5, 10), t4; 
    cout << t3 << t4; 
    return 0; 
} 
+3

你的問題是什麼?你想做什麼? – Cascabel 2012-04-09 04:53:58

+0

當我得到x = 1(a,b);之後我不知道該去哪裏。 – Jack 2012-04-09 04:54:59

+0

你是什麼意思「當我到」和「去哪兒」?你是否試圖逐行跟蹤程序的執行? – Cascabel 2012-04-09 04:56:57

回答

3
x = one(a, b); //here is my problem 
y = one(c, d); //here is my problem 

這段代碼的含義是,它調用類one的構造和這個類的新創建的實例賦值給變量xy

one類的構造是在第9行

+0

好的。那麼x和y有什麼價值? – Jack 2012-04-09 05:47:58

+0

這取決於你給'two'構造函數的值。在執行你的主類之後,你將有(for't2')'x = one(4,2)'和'y = one(8,3)'。注意你不會爲't1'創建'x'和'y',因爲它使用了其他合適的構造函數。 – Radix 2012-04-09 06:53:01

+0

@ahmadhussain'x.n'將具有值'a','x.m'將具有值'b','y.n'將具有值'c'並且'y.m'將具有值'd'。 – FlyingFoX 2012-04-09 07:02:09

3

從線x = one(a, b); 它跳轉到線 one(int a, int b) 並執行的one

同一線路y = one(c, d);

1

電流的參數的構造方法只有在一個類中有默認構造函數時纔有效。 最好在構造函數初始化列表中初始化成員:

two(int a, int b, int c, int d) 
    : x(a,b), y(c,d) 
{ 
     cout << "made one two\n"; 
} 
相關問題