在c ++上使用公共访问器的私有字段

jav*_*red 0 c++

对不起,可能是太简单的问题,我是c ++的新手.我应该如何实现int只能在类内部修改但具有公共访问器的字段?

在c#中我们可以编写这个简单的代码:

public int MsgSeqNum { get; private set; }
Run Code Online (Sandbox Code Playgroud)

在c ++上我应该写一些类似的东西(伪代码):

public:
    int GetMsgSeqNum() { return msgSeqNum; };
private:
    int msgSeqNum;
Run Code Online (Sandbox Code Playgroud)

这是正确的做事方式吗?会GetMsgSeqNum内联吗?我应该手动标记方法inline吗?我是否引入延迟添加此方法调用?

ale*_*der 7

这是正确的做事方式吗?

是的,你应该将函数返回参数标记为 const

int GetMsgSeqNum()const { return msgSeqNum; };  
Run Code Online (Sandbox Code Playgroud)

正如在评论中所提到的,const不允许你修改对象,因此如果你需要这样做,你应该使getter非const,或者声明你要在你的stil constgetter中改变的成员mutable.

GetMsgSeqNum会被内联吗?

很可能是的,在类声明中定义的任何函数都具有隐式内联.通过内联无论是显式还是隐式都不能保证函数将被内联.

我是否引入延迟添加此方法调用?

很可能没有,任何理智的编译器实现都会优化这样的调用.