1

来週、C++ のテストがあり、その準備をしています。以下に示すように、2つのクラスがあると混乱します。コードの実行を 1 行ずつ確認する必要があり、マークされた行 (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);  //here is my problem
y = one(c, d);  //here is my problem

このコードが行うことは、クラスのコンストラクターを呼び出し、oneこのクラスの新しく作成されたインスタンスを変数xおよびに割り当てることですy

class のコンストラクターはone9 行目にあります。

于 2012-04-09T05:02:50.233 に答える
3

行から行x = one(a, b); にジャンプし one(int a, int b) 、パラメーター化されたコンストラクターを実行しますone

ラインも同様y = one(c, d);

于 2012-04-09T05:11:03.530 に答える
2

現在のアプローチは、1 つのクラスにデフォルトのコンストラクターがある場合にのみ機能します。コンストラクターの初期化リストでメンバーを初期化することをお勧めします。

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 に答える