c++ - 为什么在类(c++)中声明之前使用变量(尤其是在成员函数中)不会产生编译错误?&它如何工作?

标签 c++ class


#include<iostream>

using namespace std;

 class Employee{
    public:
        Employee(char* name,int _year,float _salary)
        {
            emp_name=name;
            emp_join_year=_year;
            emp_salary=_salary;
            Printinfo();
        }
    private:

        int WorkedYear(void)
        {
            //struct date currentdate;
            int YearDiff;
            //getdate(&currentdate);
            YearDiff=2020-emp_join_year;

            return YearDiff;
        }

        void Printinfo(void)
        {
            cout << "Name      :" << emp_name << endl;
            cout << "Join Date :" << emp_join_year << endl;
            cout << "Salary    :" << emp_salary << endl;
            cout << "Worked    :" << WorkedYear() << "year(s)" << endl;
        }

        char* emp_name;
        int emp_join_year;
        float emp_salary;


};


int main()
{
    Employee john("john",1987,12500),mike("mike",1980,15500);
}

在这里我在类emp_nameemp_join_year emp_salary中使用Employee() WorkedYear() Employee在清除之前(在行中)它不会产生编译错误,但是如果我在main函数中执行此操作(即使用变量befoe /未声明),它将进行编译错误。为什么会这样?

最佳答案

直到类的定义结束为止,该类定义才被认为是“完整的”。好像所有的类方法以及所有的类成员都同时定义了。 C++标准的简短摘录:

Class members [class.mem]

A class is considered a completely-defined object type (6.8) (or complete type) at the closing } of the class-specifier . The class is regarded as complete within its complete-class contexts; otherwise it is regarded as incomplete within its own class member-specification.


从这一点开始,其余所有 Activity 部件都开始下坡。这就是为什么您似乎可以在定义类成员本身之前在内联类方法中使用类成员。
在C++之前有C,并且C必须在使用它们之前声明所有变量,并且C++继承了该变量。 C中没有类方法。当C++以及类方法和许多其他新事物出现时,C的原始部分继续按原样工作,但是C++中的新内容不必相同方式。
胶囊摘要:这就是C++的工作方式。

关于c++ - 为什么在类(c++)中声明之前使用变量(尤其是在成员函数中)不会产生编译错误?&它如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64513902/

相关文章:

c++ - 为什么无符号和有符号相减后符号不同?

c++ - 为什么这不违反单一定义规则?

C# 结构和类变量值

vba - 从用户窗体监视类事件

Java:静态类?

python - 类从哪里获得它们的默认 '__dict__' 属性?

C++ 代码命名风格转换器、格式化程序或美化程序

c++链表 - 插入对象

c++ - adjacent_find 不检测最后两个元素

c# - C# 中的匿名类