2012-04-09 286 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"; 
} 
相关问题