簡體   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