在初始化列表中初始化和在构造函数中初始化之间的区别

Pra*_*ava 1 c++

我不确定我是否正确地提出了我的问题,所以请随时纠正我.我相信:

  1. 在初始化列表中初始化相当于
    int a = a;

  2. 在构造函数中初始化相当于
    int a; a = a;

但我仍然无法弄清楚以下输出的原因:

#include <iostream>
using namespace std;

class test
{
    int a,b;
    public:

    /*
    test(int a, int b): a(a), b(b) {}         //OUTPUT: 3 2
    test(int a, int b) {   a = a; b = b;}     //OUTPUT: -2 1972965730
    test(int c, int d) {   a = c; b = d;}     //OUTPUT: 3 2 
    Hence it does work without this pointer. Unless the variable names are same
    */

    void print()    {   cout<<a<<" "<<b<<"\n";}
};

int main()
{
    test A(3,2);
    A.print();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

EDITS:

  1. 作为MM指出的等效a(a)this->a = a.

  2. 值得一读:为什么我更喜欢使用成员初始化列表?

  3. 两个解决方法是:

    test(int a, int b) {   this->a = a; this->b = b;}
    test(int a, int b) {   test::a = a; test::b = b;}
    
    Run Code Online (Sandbox Code Playgroud)

use*_*421 9

test(int a, int b) {   a = a; b = b;}
Run Code Online (Sandbox Code Playgroud)

这是不正确的.它对数据成员没有任何作用.它应该是

test(int a, int b) {   this->a = a; this->b = b;}
Run Code Online (Sandbox Code Playgroud)

  • @PrayanshSrivasta当然,其他各种事情也是如此.使用初始化列表是正确的方法. (2认同)