c++ - 在 C++ 中有 2 个类时如何知道使用哪个类?

标签 c++ constructor

<分区>

我正在为明天早上的考试做准备。我正在为下面的 C++ 演练而苦苦挣扎。 我已经运行了代码并使用 cout 来检查程序的执行情况。我注意到的第一件事是程序正在为 main 中的第一个对象调用类“one”中的默认构造函数 3 次。我真的对代码的执行感到困惑。

    #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);
      y = one(c, d);
      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;
    } 

我不明白第一件事。当main调用第一个默认构造函数时 two t1, 为什么连续调用了3次然后就会调用t2(4, 2, 8, 3);

如果代码太长,我很抱歉,但我真的需要帮助才能理解它。

请指教。谢谢。

最佳答案

我在运行代码时得到了这个结果:

one one made
one one made
one two made
one one made
one one made
made one one
made one one
made one two

这是因为:

two t1;
one one made //t1.x; parameterless 'one' constructor called by default
one one made //t1.y; parameterless 'one' constructor called by default
one two made //t1; parameterless 'two' constructor

t2(4, 2, 8, 3)
one one made //t2.x; default constructor as variable not present in initialization list

one one made //t2.y; default constructor as variable not present in initialization list

made one one //x = one(a, b) executed now
made one one //y = one(c, d) executed now
made one two //t2(int..) constructer called

请注意,在 t2 的情况下,x 和 y 被构造了两次,因为没有初始化列表。为避免这种情况,您可以使用:

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

关于c++ - 在 C++ 中有 2 个类时如何知道使用哪个类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10083242/

相关文章:

c++ - Boost::signal 内存访问错误

c++ - g++ 中的 .h 和 .H 头文件

c++ - "class"在构造函数中意味着什么?

scala - Scala 如何知道使用什么集合实现?

c# - 使用 new 的静态变量初始化会产生代码风险

c++ - 如何从 IE 中隐藏自定义工具栏

c++ - 使用 OpenCV 的低质量空中拼接

c++ - 我怎样才能像使用 wistream 从文件中读取一样从内存中读取?

C++ 奇怪的构造函数行为

c++ - 派生类构造函数中的异常