我目前正在尝试学习 C++。在学习中,我喜欢尝试一些奇怪的事情来掌握语言和内存力。现在,我正在尝试创建一个类,该类具有在构造时设置的字符数组。我类(class)的唯一方法是能够通过参数上的指针获取数组。我已经成功创建了我的类并且它工作得很好,但现在我想通过确保我永远不会更改数组的值来使其更安全。
这是我目前所拥有的:
#import <stdio.h>
class MyClass {
public:
char const * myArray;
MyClass(char inputChar[]){
myArray = inputChar;
}
void get(const char * retVal[]){
*retVal = myArray;
}
};
int main(){
char myString[] = {'H','E','L','L','O'};
MyClass somethingNew = MyClass(myString);
const char * other = new char[4];
somethingNew.get(&other);
std::cout << other[0];
return 0;
}
我注意到我根本无法使用取消引用运算符更改数组的值:
myArray[0] = 'h';
这很好,但这并不意味着我不能更改 myArray[0] 指向的指针:
*(&myArray) = new char('h');
有什么办法可以防止这种情况发生吗?
--- 分辨率 ---
#import <stdio.h>
typedef const char * const constptr;
class MyClass {
public:
constptr * myArray;
MyClass(constptr inputChar) {
myArray = &inputChar;
}
void get(constptr * retVal){
retVal = myArray;
}
};
int main(){
char myString[] = "Hello";
MyClass somethingNew(myString);
constptr other = new char[4];
somethingNew.get(&other);
std::cout << other[0];
return 0;
}
这意味着我无法执行以下任何操作:
*myArray[0] = 'h';
*myArray = new char[4];
*&*myArray = new char('h');
但是我可以这样做:
myArray = &inputChar;
最佳答案
是的,您必须像这样创建一个指向 const 对象的 const 指针:
char const * const myArray;
如您所知,第一个 const
使您无法修改指针指向的内容;第二个 const
阻止您将其他内容重新分配给指针。
您也可以考虑使用 const 引用,这几乎是一样的。
编辑:
正如 Benjamin Lindley 所指出的,由于指针现在是常量,您需要在初始化列表中为其赋值,而不是在构造函数体中,如下所示:
MyClass(char inputChar[])
: myArray(inputChar) {
}
关于c++ - 如何创建指向无法修改指向地址的数组的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13651230/