int x_ 和 int x 在C++中有什么区别

What is the difference between int x_ and int x in C++

本文关键字:int 区别 什么 C++      更新时间:2023-10-16
class Stack{
public:
char data_[100];
int top_;
};
class Stack{
public:
char data[100];
int top;
};

以上两类有什么区别?当我使用变量名称类似于int top_的类时,堆栈操作运行良好,但是当我使用带有变量int top的类时,会弹出这样的错误: 错误:成员使用无效(您是否忘记了"&"? 错误:与以前的声明冲突。 _(下划线(在此代码中的作用是什么?为什么它会产生如此大的差异?

#include<iostream>
#include<cstring>
using namespace std;
class Stack{
public:
char data[100];
int top;
bool empty()
{
return (top == -1);
}
char top()
{
return (data[top]);
}
void pop()
{
top--;
}
void push(char c)
{
data[++top] = c;
}
};
int main()
{
Stack s;
s.top = -1;
char str[10] = "ABCDEFGH";
for(int i=0;i<strlen(str);i++)
s.push(str[i]);
cout<<str<<endl;
cout<<"Reversed string is : ";
while(!s.empty())
{
cout<<s.top()<<" ";
s.pop();
}
}

_(下划线( 在此代码中的角色是什么?

它使toptop_2 个不同的标识符。就像你可以让它top1topFOOBAR一样。

为什么它会产生如此大的差异?

当您在此处使用topfor 成员时,您也与名为top的方法发生冲突。将top更改为top_top1会使该冲突消失 - 您的类中不能有 2 个不同的东西具有相同的名称。

有些人习惯于给成员变量起特殊名称,比如m_membermember_甚至_member(最后一个不安全,但有时仍然使用(。这种修饰允许读者看到代码在一侧处理成员 var,并避免像您在另一端那样发生名称冲突。