c++ - 为什么复制构造函数在C++中直接使用私有(private)属性

标签 c++ function class constructor

请看以下内容:

class node
{
    int freq;

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

    int getFreq()
    {
        return freq;
    }
};

效果很好。但是,当我用 freq = obj.getFreq() 替换 freq = obj.freq 时,它会给我这个错误:

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

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

最佳答案

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

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

因此,您不能使用 const 实例调用它:const node &obj

访问 obj.freq 是可行的,因为它适应了 const 实例,使得 obj.freq 不可修改 - 使用成员函数将是无稽之谈(缺少 const 说明符的成员函数内的代码可能(并且应该)需要可修改的实体)。

关于c++ - 为什么复制构造函数在C++中直接使用私有(private)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844477/

相关文章:

c++ - 为什么 Boost.Python 示例构建失败?

c++ - 将 double* 存储在 long (C++) 中

c++ - #include .h 和只声明 A 类之间的区别;在 C++ 中

java - 如何查找 arraylist 是否包含类字段中的值?

python - 创建类?

c++ - QSound播放.wav文件时出现意外的null接收器

c++ - 在 sizeof(++n) 表达式中不调用增量运算符

sql-server-2005 - 在SQLServer 2005函数中执行动态SQL

scala - Scala 中的单位返回函数提前返回

javascript - 如何从一个组件访问单独文件中的其他函数(非组件)的状态值? react js