从const成员函数返回指向成员数组的指针 [英] Returning a pointer to an member array from const member function

查看:57
本文介绍了从const成员函数返回指向成员数组的指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码给我一个错误

Why the following code is giving me an error

Test.cpp:23:10:错误:从'const int *'到'int *'的无效转换[-fpermissive]返回数组;

Test.cpp:23:10: error: invalid conversion from ‘const int*’ to ‘int*’ [-fpermissive] return array;

#include <iostream>
#include <stdio.h>

#define MAX_ELEMENTS 5
class CBase
{

public:
    CBase()
    {
        for(int i = 0; i < MAX_ELEMENTS; i++)
        {
            array[i] = 0;
        }
    }
    ~CBase()
    {
        // Nothing
    }
    int * GetArray() const
    {
        return array;
    }

private:
    int array[MAX_ELEMENTS];

};

int main ()
{
    CBase b;
    return 1;
}

我知道我应该返回一个const int *,但是随后我尝试了一些在下面可以正常工作的方法,要求解释允许这样做的原因,而不允许上面的原因.

I understand that I should return a const int * but then I tried something below which works fine, request to explain the reason for allowing this and not allowing the above.

#include <iostream>
#include <stdio.h>

class CBase
{
public:
    CBase():ptr(NULL)
    {
    }
    ~CBase()
    {
        delete ptr;
    }
    int * ptr;
public:
    int * GetPtr() const
    {
        return ptr;
    }
};

int main ()
{
    CBase b;

    return 1;
}

推荐答案

想象一下这样的代码:

const CBase b;
int *array = b.GetArray();
array[0] = 5; // ooops! b changed but we declared it const!?

因此,正如注释中已经提到的那样,它确实破坏了代码的const-正确性.您需要做的是声明GetArray()为非常量,或者使其返回指向const int的指针.

So as already mentioned in the comments, it does break const-correctness of your code. What you need to do is either declare GetArray() non-const, or make it return a pointer to a const int.

const int * GetArray() const 
{
    return array;
}

现在,这样的代码将无法编译:

Now, code like this would not compile:

const CBase b;
const int *array = b.GetArray();
array[0] = 5;

编辑要从上面的注释中回答您的其他问题:当您调用一个返回值的方法并将此返回值分配给某个变量时,该返回值将被复制并随后被丢弃.因此,当您的调用代码更改此变量的值时,这对最初返回的值或变量没有影响.这就是为什么const成员函数可以返回某些类的数据成员的原因.但是,当您向数据成员返回 pointer 时,调用代码可以操纵该成员的值.仍然会复制指针,但是即使复制也指向指向存储类成员的内存位置,因此您可以操纵其值.

EDIT To answer your other question from the comments above: When you call a method that returns a value and you assign this return value to some variable, than the return value is copied to your variable and afterwards discarded. So when your calling code changes the value of this variable this has no effect on the value or variable that was initially returned. That is why a const member function can return some of the class' data members. However, when you return a pointer to a data member, than the calling code can manipulate the value of this member. Still, the pointer is copied, but even the copy points to the memory location where the class member is stored and thus you could manipulate its value.

这篇关于从const成员函数返回指向成员数组的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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