C++ member functions with same name and parameters, different return type

后端 未结 5 2034
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 12:28

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

class Test {
public:
    int a;
          


        
5条回答
  •  情深已故
    2021-01-18 12:48

    To expand upon the previous answers and your given code with an example so you can actually tell what's being called when:

    #include 
    
    class Test {
    public:
        int a;
        double b;
    };
    
    class Foo {
    private:
        Test t;
    public:
        inline Test &getTest() {
            std::cout << "Non const-refrence " << std::endl;
            return t;
        }
        inline const Test &getTest() const {
            std::cout << "Const-refrence " << std::endl;
            return t;
        }
    };
    
    int main() {
        Foo foo;
        Test& t1 = foo.getTest();
        const Test& t2 = foo.getTest();
    
        const Foo bar;
        const Test& t3 = bar.getTest();
    
        return 0;
    }
    

    With output:

    Non const-refrence
    Non const-refrence
    Const-refrence
    

    The const you see after the second getTest signature tells the compiler that no member variables will be modified as a result of calling this function.

提交回复
热议问题