gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 00:38:45 25 4
gpt4 key购买 nike

下周我有一个 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;
}

最佳答案

来自行 x = one(a, b);它跳到线一个(int a,int b)并执行 one

的参数化构造函数

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

关于c++ - 在另一个类中调用一个类的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10069012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com