简体   繁体   English

使用对象而不是范围解析运算符(::)访问类中的typedef

[英]Access typedef in classes with an object, not the scope resolution operator (::)

In the following code, when I try to access the typedef with an instantiated object, it gives me an error, when I access it using the scope resolution operator (::), the program works perfectly. 在下面的代码中,当我尝试使用实例化对象访问typedef时,它给我一个错误,当我使用范围解析运算符(::)访问它时,该程序可以正常运行。 I just wanted to know why. 我只是想知道为什么。

#include <iostream>

class Types {

    public:

        typedef int Integer;

};

int main() {

    Types types;

    types.Integer foo = 1; // <-- Gives me an error

    Types::Integer goo = 2; // <-- Works perfectly fine

    std::cout << foo;
    std::cout << std::endl;
    std::cout << goo;

    return 0;

}

I'm just using this as an example, this is not real code to anything. 我只是以这个为例,这并不是任何东西的真实代码。 The error it is giving me is: 它给我的错误是:

Line 15 | invalid use of 'Types::Integer'

It's just how the syntax works. 语法就是这样工作的。 Integer in that context is a type belonging to the Types namespace, and if you want to access that type you have to use :: . 在这种情况下, Integer是一种属于Types名称空间的Types ,如果要访问该类型,则必须使用:: operator. is used for member access of objects or functions. 用于对象或功能的成员访问。

operator. allows you to access a member belonging to an instance, while :: traverses namespaces (allowing you to access static fields, static functions, typedefs, member variables, etc.). 允许您访问属于实例的成员,而::遍历名称空间(允许您访问静态字段,静态函数,typedef,成员变量等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM