在示例中,我在 getInfo() 函数之后声明并初始化了所有数据成员。我预计它会给出错误,因为成员尚未声明,但它运行良好。我很困惑它是如何工作的,因为在主函数中你必须在使用它之前声明一个变量。
#include <iostream>
#include <string>
using namespace std;
class teacher
{
public:
void getInfo() {
cout << name << endl;
cout << dept << endl;
cout << subject << endl;
cout << salary << endl;
}
teacher(string n, string de, string sub, int sal) {
name = n;
dept = de;
subject = sub;
salary = sal;
}
string name;
string dept;
string subject;
int salary;
};
int main()
{
teacher t1("Muneeb", "CS", "Civics", 2000);
t1.getInfo();
return 0;
}
我认为在 C++ 类中,成员变量在整个类中都是可见的,无论其声明顺序如何,这与必须在使用前声明的函数中的局部变量不同。