在另一个类中调用类的构造函数

时间:2012-04-09 04:49:59

标签: c++

下周我将对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;
}

3 个答案:

答案 0 :(得分:3)

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

此代码的作用是调用类one的构造函数,并将新创建的此类实例分配给变量xy

one的构造函数在第9行。

答案 1 :(得分:3)

来自x = one(a, b);行的

它跳到了线上 one(int a, int b) 并执行one

的参数化构造函数

y = one(c, d);

相同

答案 2 :(得分:1)

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

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