为什么复制构造函数直接在C ++中使用私有属性 [英] why copy constructor use private property directly in C++

查看:106
本文介绍了为什么复制构造函数直接在C ++中使用私有属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看以下内容:

class node
{
    int freq;

public:
    node(const node &other)
    {
        freq = other.freq;
    }

    int getFreq()
    {
        return freq;
    }
};

它工作得很好。但是,当我用 freq = obj.getFreq()替换 freq = obj.freq

It works well. However, when I replace freq = obj.freq with freq = obj.getFreq(), it gives me this error:

'int node::getFreq(void)': cannot convert 'this' pointer from 'const node' to 'node &'

为什么? freq 是一个私有成员,它更有意义,我们应该使用接口 getFreq 来访问它。 >

Why? freq is a private member, it makes more sense that we should use the interface getFreq to access it.

推荐答案

它不会编译,因为你的函数没有声明 const

It won't compile, because your function is not declared const:

int getFreq() const; // accessor function that does not modify the object

因此,你不能调用它< $ c> const instance: const node& obj

Thus, you can not call it with const instance: const node &obj.

访问 obj.freq ,因为它适应 const 实例,使 obj.freq 不可修改 - 使用成员函数做这件事将是一个废话(代码里面的成员函数缺少 const 说明符可能(和应该)需要可修改的实体)。

Accessing obj.freq works, because it adapts to the const instance, making obj.freq not modifiable - to do this with a member function would be a nonsense (code inside member function lacking const specifier might (and should) require modifiable entities).

这篇关于为什么复制构造函数直接在C ++中使用私有属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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