[英]Returning a pointer to an member array from const member function
為什么下面的代碼給我一個錯誤
Test.cpp:23:10: 錯誤:從 'const int*' 到 'int*' 的無效轉換 [-fpermissive] 返回數組;
#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 * 但是然后我嘗試了下面的一些工作正常的東西,請求解釋允許這個而不是允許上面的原因。
#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!?
因此,正如評論中已經提到的,它確實破壞了代碼的常量正確性。 你需要做的是要么聲明 GetArray() 非常量,要么讓它返回一個指向 const int 的指針。
const int * GetArray() const
{
return array;
}
現在,這樣的代碼無法編譯:
const CBase b;
const int *array = b.GetArray();
array[0] = 5;
編輯從上面的評論中回答你的另一個問題:當你調用一個返回一個值的方法並將這個返回值分配給某個變量時,返回值被復制到你的變量然后被丟棄。 因此,當您的調用代碼更改此變量的值時,這對最初返回的值或變量沒有影響。 這就是為什么 const 成員函數可以返回類的某些數據成員的原因。 但是,當您返回指向數據成員的指針時,調用代碼可以操作該成員的值。 盡管如此,指針還是被復制了,但即使是副本也指向存儲類成員的內存位置,因此您可以操縱它的值。
您的方法應該返回一個const int*
。
const int * GetArray() const
{
return array;
}
很簡單,您需要聲明 GetArray() 非常量,或者使其返回指向 const int 的指針。
const int * GetArray() const
{
return array;
}
原因是,如果您返回非常量數組,那么數組作為指針返回,因此它的值可以通過獲取其值的函數更改,因此常量函數間接導致更改值,因此您需要返回常量數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.