简体   繁体   English

const函数可以在本地对象上调用非const函数吗?

[英]Can const functions call non-const functions on local objects?

I have a question regarding const functions: can a const function call non-const functions on local objects in the function? 我有一个关于const函数的问题:const函数可以在函数中的本地对象上调用非const函数吗? Here's an example of what I'm talking about: 这是我正在谈论的示例:

template <class T>
Set<T> Set<T>::setUnion (const Set<T> & other) const
{
    Set<T> unionSet; //create union set
    unionSet.merge(internalStorage); //merge it with our current set
    unionSet.merge(other.internalStorage); //merge it with other set, duplicates will not be added

    return unionSet;
}

This function takes two sets and returns the union of the sets. 此函数采用两个集合并返回集合的并集。 The problem though is that the merge function is not const and the merge function also calls the add function which is also not const, so I cannot see any other way to create a union set with solely these two functions given that the setUnion function has to be const. 问题是合并函数不是const,合并函数也调用了add函数,该函数也不是const,因此,如果setUnion函数必须同时使用这两个函数,那么我看不到任何其他方法来创建联合集是常量。

PS: I know the solution without doing a const function, the reason I'm doing it this way is because my professor defined it as such. PS:我不做const函数就知道解决方案,之所以这样做是因为我的教授是这样定义的。 Thanks. 谢谢。

Yes. 是。 The only restriction on a const member function is that it can't modify the object its called on; const成员函数的唯一限制是它不能修改其调用的对象。 it can modify any other (non-const) object. 它可以修改任何其他(非const)对象。

A const member function means that the this it receives has type roughly equivalent to T const *const this 1 . const成员函数意味着它接收到的this类型大致等于T const *const this 1

That means you can't invoke any non-const functions via this , but it does not affect anything you do that doesn't go through this (explicitly or implicitly). 这意味着你可以不通过调用任何非const函数this ,但它不会影响任何你做通过走this (显式或隐式)。


1. Technically, you can't really write out the type of this truly correctly, but the type I've given here is close enough for the current discussion. 1.从技术上讲,你真的不能写出来的类型, this确实正确,但是我在这里给出的类型是目前的讨论非常接近。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM