我正在尝试对真正 const 的类进行 const 操作 - 它不会更改类指向的数据。
例如:
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
}
};
您可以使用模板在指针上强制执行常量正确性,而无需更改类的含义或实现:
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
函数声明后表示不允许函数更改任何类成员(标记为 mutable
的类成员除外)。
由于您的代码不会更改任何类成员,并且只更改node
指向的对象,因此这两个函数都将编译。
AFAIK 没有办法阻止这种情况。如果你标记node
const
,两者都不会编译。
你混淆了Node* const
Node const*
.
在这里使用间接寻址的一个[不幸的?]副作用是指针成员的const
性与您正在操作的实际Node
无关。
如果您不需要该成员作为指针,那么这非常简单:
class V
{
public:
Node node;
void const_action() const
{
node.val = 5; // error here
}
void action()
{
node.val = 5; // no error here
}
};
然而,鉴于它的名字,我怀疑生活并没有那么简单,你基本上不走运。