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. 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 ::
. 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.).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.