C++ 何时使用 -> 或 ::
C++ When do I use -> or ::
我知道在C++中,您使用->
或::
而不是C#等语言中的.
来访问对象的值,例如 button->Text
或System::String^
,但我不知道什么时候应该使用->
或::
,这非常令人沮丧,因为它会导致我许多编译器错误。如果您能提供帮助,我将不胜感激。谢谢:)
->
是当您访问指针变量的成员时。 EG:myclass *m = new myclass(); m->myfunc();
在指向myclass
的指针上调用myfunc()
。 ::
是范围运算符。这是为了显示某物在什么范围内。 因此,如果myclass
在命名空间foo
中,那么您将编写foo::myclass mc;
-
->
,如果您有指向某个对象的指针,这只是取消引用该指针并访问其属性的快捷方式。pointerToObject->member
与(*pointerToObject).member
相同 -
::
用于从某个范围访问内容 - 它仅适用于命名空间和类/结构范围。namespace MyNamespace { typedef int MyInt; } MyNamespace::MyInt variable;
与您的问题所述相反,您确实在C++中使用了.
。相当多。
.
(与非指针一起使用以访问成员和方法)
std::string hello = "Hello";
if (hello.length() > 3) { ... }
->
(与用于访问成员和方法的指针一起使用)
MyClass *myObject = new MyClass;
if (myObject->property)
myObject->method();
::
(范围解析)
void MyClass::method() { ... } //Define method outside of class body
MyClass::static_property; //access static properties / methods
::
也用于命名空间解析(请参阅第一个示例 std::string
,其中 string
位于命名空间std
中)。
我试图展示一些::
、.
和->
用法的例子。我希望它有帮助:
int g;
namespace test
{
struct Test
{
int x;
static void func();
};
void Test:: func() {
int g = ::g;
}
}
int main() {
test::Test v;
test::Test *p = &v;
v.x = 1;
v.func();
p->x = 2;
p->func();
test::Test::func();
}
当
左操作数是指针时应用 Opertor ->。例如考虑
struct A
{
int a, b;
A( int a, int b ) : a( a ), b( this->a * b ) {}
};
运算符 :: 引用正确操作数所属的类或空间。例如
int a;
strunt A
{
int a;
A( int a ) { A::a = a + ::a; }
};
使用句点,然后左操作数是对象的左值。例如
struct A
{
int x;
int y;
};
A *a = new A;
a->x = 10;
( *a ).y = 20;
相关文章:
- 何时在引用或唯一指针上使用移动语义
- 如何在 C 中正确使用 libiconv 使其不会报告"Arg list too long"?
- std::vector的包装器,使数组的结构看起来像结构的数组
- 何时提供默认参数作为模板参数
- 如何在全屏模式下(在OpenGL中)使背景透明
- 找到两对数字,使它们的乘积的绝对差最小化
- C++:如何使函数只返回作为列表一部分的字符串
- C++-明确何时以及如何调用析构函数
- c++使用foreach使数组为null
- 使外部项目可用于find_package CMake
- 不确定要在我的main中放入什么才能使我的代码正常工作
- EASTL矢量<向量<int>>连续的
- 是否可以在C++中使变量真正只读
- 有可能使shared_ptr协变吗
- 使lambda不可复制/不可移动
- 何时使函数成为类成员函数C++?
- 何时必须使操作员<<过载?
- 在Windows上,何时有必要将附加到目录路径上,以使_stat成功
- Apple C++ LLVM Compiler 4.x & UNICODE:何时需要?UNICODE 是默认编译器字符集吗?使代码同时编译 ANSI 和 UNICODE 版本
- 如何使libcurl c++调用超时和/或知道调用中何时发生超时