谁能解释一下上面的代码是如何工作的以及使用哪个概念

Can anyone explain me how above code works and using which concept?

本文关键字:工作 一下 能解释 代码 何工作      更新时间:2023-10-16
 #include<iostream>
  using namespace std;
    class A
   {
   public:
   A(int x)
   {
   a=x;
    }
   int a;
    };
  void fun(A temp)
  {
  cout<<temp.a<<endl;
  }
  int main()
  {
  fun(1);
   }

在这里,我们将原始值传递给有趣的方法并使用 A类的对象。 谁能解释一下上面的代码是如何工作的以及使用哪个概念?

我为您注释了代码,并使其阅读起来更清晰一些。阅读 (1( -> (5( 中的评论。

#include <iostream>
using namespace std;
class A {
public:
    A(int x) // (3): gets called by f to initialize an object of class A with x=1
    {
        a = x;
    }
    int a;
};
void fun(A temp) // (2): Assumes 1 is a type class A. But it hasn't yet been initialized. So it calls Constructor. (tmp = new A(1))
{
    // (4): Now temp is an object of class A
    cout << temp.a << endl; // Prints temp.a
    // (5): temp object is getting destroyed.
}
int main()
{
    fun(1); // (1): Calls fun() with argument of 1
}

类 A 有一个构造函数,它接收一个整数作为参数。

因此,传递给 fun 的整数参数会自动转换为 A。

在此自动转换过程中,将创建一个 A 对象(称为 temp(,其字段"a"初始化为 1。