c ++ const成员函数返回一个const指针。但是什么类型的const是返回的指针? [英] c++ const member function that returns a const pointer.. But what type of const is the returned pointer?

查看:77
本文介绍了c ++ const成员函数返回一个const指针。但是什么类型的const是返回的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这已经被问过,我要表示歉意,但是如何在c ++中创建一个返回以下scenerios中的指针的成员函数:
1.返回的指针是常量,但是里面的垃圾可以修改。
2.里面的junk是常数,但返回的指针可以修改。
3.既不能修改垃圾,也不能修改指针。



是这样的:


  1. int * const func()const

  2. const int * func()const

  3. const int * const func()const



注意:
如果我的方法声明为const,那么教程会说我'm说明我不会修改参数..但是这不够清楚,在我的情况下,当一个参数是一个指针。我的参数需要如下:



a。 void func(const int * const x)const;

b。 void func(const int * x)const;

c。 void func(const int * const x)const;

解决方案

I不知道你已经读了什么书,但是如果你标记一个方法const,这意味着这将是类型 const MyClass * 而不是 MyClass * ,这反过来意味着你不能更改未声明为 mutable ,也不能调用任何非const方法。



现在返回值。



1。 int * const func()const



函数是常量,返回的指针是常量,里面可以修改。但是,我看不到返回一个const指针,因为最终的函数调用将是一个右值,非类型的rvalues不能 const ,意味着 const 将被忽略



2。 const int * func()const



这是一个有用的事情。 junk inside不能修改



3。 const int * const func()const



在语义上几乎与2相同, / p>

HTH


I apologize if this has been asked, but how do I create a member function in c++ that returns a pointer in the following scenerios: 1. The returned pointer is constant, but the junk inside can be modified. 2. The junk inside is constant but the returned pointer can be modified. 3. Neither the junk, nor the pointer can be modified.

Is it like so:

  1. int *const func() const
  2. const int* func() const
  3. const int * const func() const

All of the tutorials I've read don't cover this distinction.

Side note: If my method is declared const then the tutorials say that I'm stating that I won't modify the parameters.. But this is not clear enough for me in the case when a parameter is a pointer. Do my parameters need to be like:

a. void func(const int* const x) const;
b. void func(const int* x) const;
c. void func(const int* const x) const;

解决方案

I don't know what book you have read, but if you mark a method const it means that this will be of type const MyClass* instead of MyClass*, which in its turn means that you cannot change nonstatic data members that are not declared mutable, nor can you call any non-const methods.

Now for the return value.

1 . int * const func () const

The function is constant, and the returned pointer is constant but the 'junk inside' can be modified. However, I see no point in returning a const pointer because the ultimate function call will be an rvalue, and rvalues of non-class type cannot be const, meaning that const will be ignored anyway

2 . const int* func () const

This is a useful thing. The "junk inside" cannot be modified

3 . const int * const func() const

semantically almost the same as 2, due to reasons in 1.

HTH

这篇关于c ++ const成员函数返回一个const指针。但是什么类型的const是返回的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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