“::”之间的区别是什么? “。”。和“ - >”。在c ++ [英] What is the difference between "::" "." and "->" in c++

查看:184
本文介绍了“::”之间的区别是什么? “。”。和“ - >”。在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

我创建了一个名为Kwadrat的类三个int字段内。代码块给了我一个建议,我可以通过 :: - > 。箭头是唯一的工作,但为什么?这三个之间有什么区别?

I have created the class called Kwadrat and I have three int fields inside. The Code Blocks gives me advice that i can get into the field of the object by ::, . and ->. The arrow is the one that only works, but why? What's the difference between those three?

#include <iostream>

using namespace std;

class Kwadrat{
public:
int val1, val2, val3;
    Kwadrat(int val1, int val2, int val3)
    {
        this->val1 = val1;
        //this.val2 = val2;
        //this::val3 = val3;
    }
};

int main()
{
    Kwadrat* kwadrat = new Kwadrat(1,2,3);
    cout<<kwadrat->val1<<endl;
    cout<<kwadrat->val2<<endl;
    cout<<kwadrat->val3<<endl;
    return 0;
}


推荐答案

1。 - > 用于通过指针访问对象成员变量和方法

1.-> for accessing object member variables and methods via pointer to object

Foo *foo = new Foo();
foo->member_var = 10;
foo->member_func();

2。和方法通过对象实例

2.. for accessing object member variables and methods via object instance

Foo foo;
foo.member_var = 10;
foo.member_func();

3。 :: 以及 class / struct 命名空间的方法。它还可以用于从另一个范围访问变量和函数(实际上,类,结构,命名空间都是范围)

3.:: for accessing static variables and methods of a class/struct or namespace. It can also be used to access variables and functions from another scope (actually class, struct, namespace are scopes in that case)

int some_val = Foo::static_var;
Foo::static_method();
int max_int = std::numeric_limits<int>::max();

这篇关于“::”之间的区别是什么? “。”。和“ - >”。在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆