命名重载的getter方法:const和非const [英] naming the overloaded getter methods : const and non-const

查看:144
本文介绍了命名重载的getter方法:const和非const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

class A
{
  public:
    B* get_b() const;

    const B* get_b() const;
};

这是非法的,因为2重载的方法只在返回类型中有区别。但语义上他们正是我想要的:两个函数都不应该修改A对象这些方法内,而第一个允许调用者修改对象之后调用该方法。

This is illegal because the 2 overloaded methods only diff in the return type. But semantically they are exactly what I want: neither function should modify the A object "inside these methods" while the first allows the caller to modify the object "after" calling the method.

我看到2个解决方案:
1.从第一个方法中删除const,因为即使方法本身不修改对象,它返回一个非const数据,稍后可以修改。

I see 2 solutions: 1. Remove const from the first method because even the method itself does not modify the object, it returns a non-const data which could be modified later.


  1. 以不同的方式命名方法

你看到了吗?

[UPDATE]
好​​的,我想我应该删除第二个。推理是方法应该只关注自身(方法修改对象或不修改对象),并且不应该限制客户端如何使用数据(如果数据可能被修改)。

[UPDATE] OK, I guess I should just remove the 2nd one. The reasoning is the method should just focuses on itself(the method modifies the object or not) and should not restrict how the client uses the data(if the data can potentially be modified).

推荐答案

在C ++中,你不能通过返回类型重载一个函数 - 就是这样。考虑一个例子:

In C++, you cannot overload a function by return type - that's it. Consider an example:

int GetValue();
float GetValue();

// Call it
GetValue(); // Which one?

您不是将返回值赋给任何值,或使用 GetValue 在任何表达式中,您(读者)无法确定将调用哪个函数。即使您指定:

You aren't assigning the return value to any value, or using GetValue in any expression, you (reader) cannot figure out which function will be called. Even if you assign:

double x = GetValue();

并且假设编译器可以根据返回类型进行推导,因为两者的返回值( int float )可以转换为 double 。简而言之,该语言不允许基于返回类型的函数重载,而不管 const ,指针或引用类型添加到返回类型。

And assuming that compiler can deduce based on return type, there is still ambiguity - which function to call, since return value of both (int, and float) can be converted to double. In short, the language doesn't allow function overload based on return type, irrespective of const, pointer or reference type added to return type.

这篇关于命名重载的getter方法:const和非const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆