1

下周我有一个 C++ 测试,我正在为此做准备。当我有 2 个班级时,我很困惑,如下所示。我必须逐行执行代码,并且我对标记的行(x = ...y = ...内部class two)感到困惑-执行从那里去哪里?

#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;
}
4

3 回答 3

3

从该行x = one(a, b); 跳转到该行 one(int a, int b) 并执行参数化构造函数one

线相同y = one(c, d);

于 2012-04-09T05:11:03.530 回答
3
x = one(a, b);  //here is my problem
y = one(c, d);  //here is my problem

这段代码所做的是它调用类的构造函数one并将新创建的这个类的实例分配给变量xy

类的构造函数one在第 9 行。

于 2012-04-09T05:02:50.233 回答
2

当前方法仅在一个类中有默认构造函数时才有效。最好在构造函数初始化列表中初始化成员:

two(int a, int b, int c, int d) 
    : x(a,b), y(c,d)
{
        cout << "made one two\n";
}
于 2012-04-09T07:01:28.253 回答