具有相同名称和参数,不同返回类型的C ++成员函数 [英] C++ member functions with same name and parameters, different return type

查看:67
本文介绍了具有相同名称和参数,不同返回类型的C ++成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在这样的类中定义具有相同名称和参数但返回类型不同的成员函数是否有效?

is it valid if I define member functions with same name&parameters but different return types inside a class like this:

class Test {
public:
    int a;
    double b;
}

class Foo {    
private:
    Test t;
public:
    inline Test &getTest() {
        return t;
    }
    inline const Test &getTest() const {
        return t;
    }
}

如果我们有以下代码,哪个成员函数会被调用?

Which member function gets called if we have following code?

Foo foo;  // suppose foo has been initialized
Test& t1 = foo.getTest();
const Test& t2 = foo.getTest();

推荐答案

否,它无效,但是在您的示例中是有效的,因为最后一个 const 实际上是签名(隐藏的 Foo * this 第一个参数现在为 const Foo * this ).

no, it is not valid, but in your example it is, because the last const is actually part of the signature (the hidden Foo *this first parameter is now const Foo *this).

它用于以只读方式访问(获取const引用,方法是常量),或进行写入(获取非const引用,方法不是常量)

It is used to access in read-only (get const reference, the method is constant), or write (get non-const reference, the method is not constant)

在两种方法中都返回相同实体(常量或非常量)的引用仍然是一个不错的设计选择!

it's still a good design choice to return the reference of the same entity (constant or non-constant) in both methods of course!

这篇关于具有相同名称和参数,不同返回类型的C ++成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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