具有相同名称的C ++变量,context:global和private,

时间:2021-11-30 08:26:03

In the following code, g++ gives this error : 1.cpp: In member function void W::test()': 1.cpp:6: error:int F::glob' is private 1.cpp:19: error: within this context

在下面的代码中,g ++给出了这个错误:1.cpp:在成员函数中void W :: test()':1.cpp:6:error:int F :: glob'是private 1.cpp:19:error:在这种背景下

But, shouldn't the globally declared variable 'glob' be used here, instead of the "private" "glob"?

但是,不应该在这里使用全局声明的变量'glob',而不是“私有”“glob”吗?

   #include <iostream.h>

    int glob;
    class F
    {
        int glob;
        public:
        void readIt()
        {
            cin >> glob;
        }
    };

    class W : public F
    {
        public:
            void test()
            {
                glob--;
            }
    };

    int main()
    {
    }

4 个解决方案

#1


Variables and functions are accessed using scoping rules, not visbility rules. Because F::glob is the glob in the scope of W::test(), it is used. However, W::test() does not have access to F::glob, and an error results. The compiler does not check for ::glob because something else preceeds it in scope "priority" (not sure for the exact term).

使用范围规则访问变量和函数,而不是可见性规则。因为F :: glob是W :: test()范围内的glob,所以使用它。但是,W :: test()无法访问F :: glob,并且会产生错误。编译器不会检查:: glob,因为在“优先级”范围内还有其他东西(对于确切的术语不确定)。

#2


private glob shadows the global glob,so the error is correct use ::glob to access the global variable if u intent to use global variable

private glob会影响全局glob,所以错误是正确的使用:: glob来访问全局变量,如果你打算使用全局变量

#3


You can try using ::glob--; instead. This way you tell the compiler to use the global namespace.

你可以尝试使用:: glob--;代替。这样就告诉编译器使用全局命名空间。

#4


Class member will be used here, to access global variable use :: operator.

这里将使用类成员来访问全局变量use :: operator。

#1


Variables and functions are accessed using scoping rules, not visbility rules. Because F::glob is the glob in the scope of W::test(), it is used. However, W::test() does not have access to F::glob, and an error results. The compiler does not check for ::glob because something else preceeds it in scope "priority" (not sure for the exact term).

使用范围规则访问变量和函数,而不是可见性规则。因为F :: glob是W :: test()范围内的glob,所以使用它。但是,W :: test()无法访问F :: glob,并且会产生错误。编译器不会检查:: glob,因为在“优先级”范围内还有其他东西(对于确切的术语不确定)。

#2


private glob shadows the global glob,so the error is correct use ::glob to access the global variable if u intent to use global variable

private glob会影响全局glob,所以错误是正确的使用:: glob来访问全局变量,如果你打算使用全局变量

#3


You can try using ::glob--; instead. This way you tell the compiler to use the global namespace.

你可以尝试使用:: glob--;代替。这样就告诉编译器使用全局命名空间。

#4


Class member will be used here, to access global variable use :: operator.

这里将使用类成员来访问全局变量use :: operator。