c++ - 与同一类的私有数据成员具有相同名称的成员函数的变量会发生什么?
问题描述
当我编译下面的代码时,我没有收到任何错误,并且在调试时它将类的类数据成员初始化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;
}
解决方案
这就是所谓的“可变阴影”。
当你这样做时,局部变量会a
“隐藏”类变量。编译器将使用局部变量,因此在inivalue
类的函数中,abc
您只需将参数值设置为自身。
类的a
成员在使用时会被单化,max
代码会导致Undefined Behaviour。
推荐阅读
- android - 在 RecyclerView 中清除了 EditText onSubmit 函数
- python - 使用 dask 在网格上广播并行函数的问题
- python - 提供保存我的模型的路径。(/content/drive/My Drive/training) ,但“我的驱动器”中的空间会引发错误
- google-apps-script - 如何使用谷歌应用脚本从单独的数据构建日期?
- node.js - Electron 作为 Web 浏览器的安全隐患
- powershell - 用于修改 zip 文件夹中的 .dat 文件的 Powershell 脚本
- r - 关闭应用程序后保存对数据表所做的更改 (R)
- javascript - 在 JavaScript ES6 中,可迭代对象和迭代器有什么区别?
- java - 从活动中获取数据到 RecyclerView 适配器?
- c++ - 抛出异常:读取访问冲突。它是 0xFFFFFFFFFFFFFFFF