本文介绍了如何保持const指针的正确性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
p> class Node {
public:
int val;
};
class V {
public:
Node * node; //这里需要的改变是什么?
void const_action()const {
node-> val = 5; //错误想要这里
}
void action(){
node-> val = 5; //错误不在这里
}
};
解决方案
您可以使用模板来强制const正确性一个不改变类的含义或实现的指针:
template< typename T&
class PreseveConstPointer
{
T * t_;
public:
PreseveConstPointer(T * t = nullptr)
:t_(t)
{
}
PreseveConstPointer& * operator =(T * t)
{
t_ = t;
return this;
}
T * operator->()
{
return t_;
}
T const * operator->()const
{
return t_;
}
T * data()
{
return t_;
}
};
class Node {
public:
int val;
};
class V {
public:
PreseveConstPointer< Node>节点;
V()
{
node = new节点;
}
〜V()
{
if(node.data())
delete node.data();
}
void const_action()const {
node-> val = 5; //你会得到一个错误
}
void action(){
node-> val = 5; // No error here
}
};
I am trying to have a const operation on a class that is truly const - it does not change data that the class points to.
For example:
class Node{
public:
int val;
};
class V{
public:
Node * node; //what is the change that is needed here?
void const_action()const{
node->val=5; //error wanted here
}
void action(){
node->val=5; //error is not wanted here
}
};
解决方案
You can use a template to enforce the const correctness on a pointer without changing the meaning or the implementation of your class:
template <typename T>
class PreseveConstPointer
{
T *t_;
public:
PreseveConstPointer(T *t = nullptr)
: t_(t)
{
}
PreseveConstPointer<T> * operator=(T *t)
{
t_ = t;
return this;
}
T* operator->()
{
return t_;
}
T const * operator->() const
{
return t_;
}
T * data()
{
return t_;
}
};
class Node{
public:
int val;
};
class V{
public:
PreseveConstPointer<Node> node;
V()
{
node = new Node;
}
~V()
{
if(node.data())
delete node.data();
}
void const_action()const{
node->val=5; // You will get an error here
}
void action(){
node->val=5; // No error here
}
};
这篇关于如何保持const指针的正确性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!