一个关于C++的问题
伊谢尔伦
伊谢尔伦 2017-04-17 13:01:01
0
4
554

有以下两段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行不同),为什么运行结果就不一样呢?

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

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(4)
小葫芦

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

刘奇

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++.

黄舟

"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).

Peter_Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!