使用getter函数返回成员对象作为const,但它是可修改的

时间:2015-05-15 14:55:43

标签: c++

我有一个私有成员的类,它是一个对象,我已经设置了一个相应的getter:

class lepton {
private:
  TLorentzVector _p;
  ...

public:
  ...
  const TLorentzVector& p() const { return _p; }
};

并且TLorentzVector类当然有自己的函数和变量,例如,假设SetStuff(...)是一个函数。我们还要说SetStuff(...)修改了对象的私有变量。我的程序允许我打电话:

....
lepton foo;
foo.p().SetStuff(...);
....

我想知道这是如何可能的,因为getter p()是const。 这是一个允许修改类成员的getter的坏方法吗?我最终得到了这个设置,因为在我的程序中的另一个点我想添加两个对象的_p(TLorentzVector对象)变量,如下所示:

lepton lep1;
lepton lep2;
....
auto combined_four_vector = lep1.p() + lep2.p();
....

如果我把lepton类中的getter定义为:

TLorentzVector& p() { return _p; }

我无法添加TLorentzVector对象。

1 个答案:

答案 0 :(得分:3)

您可以定义非常量重载和常量重载(除非您有任何理由不定义非常量重载):

class lepton {
    // ...
public:
    // ...
    TLorentzVector const& p() const { return _p; }
    TLorentzVector& p() { return _p; }
};

通过这种方式,对于仅lepton const&采用const的函数和运算符,可以使用lepton foo; foo.p().SetStuff(...); 重载,从而保持对象的const安全性。

例如,以下内容将按预期工作:

operator+

并假设在TLorentzVector const&上定义auto res = lep1.p() + lep2.p(); ,以下内容也可以正常使用:

$(document).ready(function () {
        var url = 'http://localhost:8080/api/Values';
        $.ajax({
            url: url,
            type: 'POST',
            crossdomain: 'true',
            contentType: "application/json; charset=utf-8;",
            type: 'GET',
            success: function (result) {
                var r = JSON.stringify(result);
                alert("From Web-API  " + r);
            }
        });
});
相关问题