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();
}
}
最佳答案
What is the role of the _(underscore) in this code ?
它使 top
和 top_
成为 2 个不同的标识符。同样的方法,你可以让它成为 top1
或 topFOOBAR
。
Why is it making such a difference ?
当您在这里使用 top
作为 member 时,您也会与名为 top
的方法发生冲突。将 top
更改为 top_
或 top1
将使冲突消失 - 你不能在你的类中有 2 个不同的东西同名。
有些人习惯给成员变量起特殊的名字,比如 m_member
或 member_
甚至 _member
(最后一个不安全但是有时仍然使用)。这种装饰使读者可以看到代码在一侧处理成员 var,并避免像在另一侧那样的名称冲突。
关于c++ - C++ 中的 int x_ 和 int x 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52008580/