首页 > 解决方案 > 与同一类的私有数据成员具有相同名称的成员函数的变量会发生什么?

问题描述

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

//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;
}

标签: c++

解决方案


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

当你这样做时,局部变量会a“隐藏”类变量。编译器将使用局部变量,因此在inivalue类的函数中,abc您只需将参数值设置为自身。

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


推荐阅读