繁体   English   中英

与同一类的私有数据成员同名的成员函数的变量会发生什么?

[英]What happens to a variable of a member function having same name as that of a private data member of the same class?

当我编译下面的代码时,我没有收到任何错误,并且在调试时它将类abc的类数据成员a初始化为零。 有人可以告诉我编译器如何区分两者。 我没有看到它在运行时发生。

//A function friendly to two classes (finding maximum of objects of 2 classes(one data member in class)
#include <iostream>
#include <conio.h>
using namespace std;

class abc; //Forward Declaration
class xyz
{
  int x;
  public :
  void inivalue(float);
  friend float max(xyz,abc);
};

class abc
{
  int a;
  public :
  void inivalue(float);
  friend float max(xyz,abc);
};

void xyz::inivalue(float y)
{
  x=y;
}

void abc::inivalue(float a)
{
  a=a;
}

float max(xyz m,abc n)
{
  if(m.x > n.a)
  return m.x;

  else
  return n.a;
}

int main()
{
  system("cls");
  xyz o1;
  abc o2;
  o1.inivalue(10);
  o2.inivalue(20);
  cout<<"The maximum of 2 classes is : "<<max(o1,o2)<<endl;
}

这就是所谓的“可变阴影”。

当你这样做,局部变量a “阴影”之类的变量。 编译器将使用局部变量,因此在类abcinivalue函数中,您只需将参数值设置为自身。

类的a成员在max使用时会被单元化,代码将导致 Undefined Behaviour。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM