指针和参考 [英] pointers and references

查看:60
本文介绍了指针和参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是c ++的新手.我无法理解的一件事. *或&是什么类方法名称之前是什么意思?我也通过简单的功能看到了它.例如,这里的类方法返回this指针,但是什么是&"为了?如果此类方法更改了对象,那么const又是什么呢?

Hi, i''m new at c++. There is one thing I can''t understand. What do * or & before class method name mean? Also I have seen it after simple functions. For example, here class method returns the this pointer, but what is "&" for? Also what is const for if this class method changes object?

const Counter& Counter::operator++()
   {
       ++itsVal;
       return *this;
    }

推荐答案

在方法名之前不是"*"或&",而是"'*'或'&键入后.

例如:
It isn''t a ''*'' or an ''&'' before a method name, it''s a ''*'' or an ''& after a type.

For example:
int * fun(int p)
   {
   }

是说名为"fun"的函数返回一个指向整数的指针. *是指int而不是fun. &"也是如此:它将返回对整数的引用.

在您给出的示例中,class方法不会返回this指针"-它返回对项目this所指向的点的引用(该类的实例)-参见this之前的"*"吗?

Is saying that the function called "fun" returns a pointer to an integer. The ''*'' refers to the int not the fun. The same applies for ''&'': it would return a reference to an integer.

In the example you give, teh class method does not "return the this pointer" - it returns a reference to the item this points at (the instance of the class) - see the ''*'' before this?


这不只是在类之前",而是这是运算符"++"的返回类型的规范的一部分.
您具有类型SomeType,符号SomeType&表示另一种类型,对类型SomeType的实例的引用",并且consts使常量修改的变体成为同一类型,即符号const SomeType&表示对SomeType类型的实例的引用;该实例无法通过该引用进行修改".

这种const修改可以被认为是语法糖,并且是一种愚蠢的功能,可以保护类型变量免受实例的修改,但是变量本身的值可以修改,因为您以后可以为它分配相同类型的其他引用.

C ++引用在这里得到了很好的解释,包括它们的语义和用法:
http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29 [^ ].

—SA
This is not just "before class", rather, this is the part of the specification of the return type of the operator "++".

You you have a type SomeType, the notation SomeType& means another type, "a reference to the instance of the type SomeType", and the consts makes the constant-modified variant the the same type, that is, the notation const SomeType& means "a reference to the instance of the type SomeType; and the instance cannot be modified through this reference".

This const modification can be considered as syntactic sugar and a fool-proof feature protecting the variable of the type const SomeType& from modification of the instance, but the value of the variable itself can be modified, as you can assign a different reference of the same type to it later on.

C++ references are well explained here, with their semantics and usage:
http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29[^].

—SA


这篇关于指针和参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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