对我所假设的问题抱歉是非常基本的.
我无法在网上找到operator ::和之间的区别.在C++中
我有几年的C#和Java经验,熟悉使用的概念.成员访问的运营商.
任何人都可以解释这些将被使用的时间和区别是什么?
谢谢你的时间
Joh*_*0te 23
区别在于第一个是范围解析运算符,第二个是成员访问语法.
因此,::(范围解析)可用于在命名空间中进一步访问某些内容,如嵌套类,或访问静态函数.该.期间运营商将简单地访问你使用它的类实例的任何可见的成员.
一些例子:
class A {
public:
class B { };
static void foo() {}
void bar() {}
};
//Create instance of nested class B.
A::B myB;
//Call normal function on instance of A.
A a;
a.bar();
//Call the static function on the class (rather than on an instance of the class).
A::foo();
Run Code Online (Sandbox Code Playgroud)
请注意,静态函数或数据成员是属于类本身的成员,无论您是否已创建该类的任何实例.所以,如果我在我的类中有一个静态变量,并且包含了该类的一千个实例,那么该静态变量只有一个实例.但是,任何其他成员的1000个实例都不是静态的,每个类的实例一个.
当你来到它时,还有一个有趣的选择:)你还会看到:
//Create a pointer to a dynamically allocated A.
A* a = new A();
//Invoke/call bar through the pointer.
a->bar();
//Free the memory!!!
delete a;
Run Code Online (Sandbox Code Playgroud)
如果你尚未学习动态内存可能会有点混乱,所以我不会详细介绍.只是想让你知道你可以使用{ ::或.或->} 访问成员:)
在C++中::是范围解析运算符.它用于区分名称空间和静态方法,基本上任何情况下你都没有对象.凡.用于访问对象内的事情.
C#.对它们都使用运算符.
namespace Foo
{
public class Bar
{
public void Method()
{
}
public static void Instance()
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
在C#中你会写这样的代码:
var blah = new Foo.Bar();
blah.Method();
Run Code Online (Sandbox Code Playgroud)
但是等效的C++代码看起来更像是这样的:
Foo::Bar blah;
blah.Method();
Run Code Online (Sandbox Code Playgroud)
但请注意,也可以使用范围解析运算符访问静态方法,因为您没有引用对象.
Foo::Bar::Instance();
Run Code Online (Sandbox Code Playgroud)
同样,C#代码只使用点运算符
Foo.Bar.Instance();
Run Code Online (Sandbox Code Playgroud)