search

Home  >  Q&A  >  body text

一个关于C++的问题

有以下两段C++代码。第一段为:

#include<iostream>
#include<cstdlib>
using namespace std;

class Pair{ 
public:
    Pair(int a, int b): ma(a), mb(ma+b) {}
    int ma;
    int mb;
};

int main(){
    Pair p(1,2);
    cout << p.ma << " " << p.mb << endl;
    system("pause");
    return 0;
}

运行结果为:
1 3

第二段代码为:

#include<iostream>
#include<cstdlib>
using namespace std;

class Pair{ 
public:
    Pair(int a, int b): ma(a), mb(ma+b) {}
    int mb;
    int ma;
};

int main(){
    Pair p(1,2);
    cout << p.ma << " " << p.mb << endl;
    system("pause");
    return 0;
}

运行结果为:
1 -858993458

两段代码,仅仅是成员变量 ma、mb 的定义顺序不同(第8行、9行不同),为什么运行结果就不一样呢?

百思不得姐!!希望大神指点一二,谢谢。

伊谢尔伦伊谢尔伦2803 days ago625

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:03:01

    Please pay attention to the rules for using so-called initializers
    They do not determine who is initialized first according to the position of the initializer
    but based on who initializes the variable first.

    Because mb comes first in the second piece of code, mb will be initialized first.
    The details should be available in C++ Primer 5ed. My personal suggestion is not to use mutual references for initialization

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 13:03:01

    This is related to the order of variable initialization. In the second piece of code, mb is first, so mb is initialized first, but ma has not been initialized yet. It is a random number, so mb will not be 3. The order of variable initialization in the C++ class constructor is only related to the order of variable definition, and has nothing to do with the order of the initialization list in the constructor. Because the initialization order of member variables is related to the order of variables in memory, and the arrangement order in memory is determined as early as the compile time based on the definition order of variables. This is described in detail in EffectiveC++.

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:03:01

    "c++ primer" (Chinese 4th edition) says: The constructor initialization list only specifies the values ​​used to initialize members, and does not specify the order in which these initializations are performed.

    In other words, what you encounter is an undefined behavior, which depends on the specific implementation of the compiler. If the compiler initializes class members in the order they appear, then the first example is correct, and the second example is incorrect (because mb loses the chance to be initialized).

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:03:01

    The answers from several masters are very good. I have no choice but to accept one answer. I will give it to the master who answered first

    reply
    0
  • Cancelreply