C++ - 对 const 感到困惑

C++ - confused about const

我正在阅读有关 const 对象的教程 http://www.learncpp.com/cpp-tutorial/810-const-class-objects-and-member-functions/

我了解 const 对象只能访问 const 函数。令我困惑的是,当我们将 const 对象传递给复制构造函数时,它如何访问非 const 函数?

示例:

class Dog {
     protected:
         string m_name;
         int m_age; 
     public:
         Dog() : m_name("Fido"), m_breed("Corgi"), m_color("Black"), m_age(1) {}
         Dog(const Dog& d) { m_name = d.getName(); m_age = d.getAge(); }
         String getName() { return m_name; }
         int getAge() { return m_age; }
};

那么当用const dog对象调用拷贝构造函数时,这个对象如何访问getName()和getAge()函数呢?

const 成员函数是不能修改被调用的 class 实例的成员函数。

因此,如果您有一个 const 对象,您只能通过在函数原型后附加 const 来调用声明为 const 的函数:

void const_function(int i) const { /* function body */ }
                           ^^^^^

那是唯一可以出现const的地方,为了实现const的功能。其他地方只是修改 return 类型或参数。


A copy constructor 只是一个构造函数,它将 const 对同一类型对象的引用 作为参数。引用是 const 因为构造函数 不修改 作为参数传递的对象,它只是 从它复制 并构造新的具有复制数据的对象:

Foo(const Foo& copy_from_this_object) { /* copy member data from argument */ }

此外,复制构造函数实际上并没有从它的参数中复制 constness,它只是从中复制所有数据。 IE。参数是否为 const 并不重要,它只是 copied,而不是 修改。新构造的可能会也可能不会const。它与复制自对象的 constness 无关。


编辑(OP编辑后):

So when the copy constructor is called with a const dog object, how can this object access the getName() and getAge() functions?

不能.

这是因为成员函数没有正确标记 const 他们应该有:

getNamegetAge 不要修改它们的 class 实例 。因此他们应该是const!在使它们成为 const 之后,它们可以在复制构造函数中的 const 对象上被调用,并且代码可以正常编译。

注意:一般来说,你应该总是制作吸气剂const。那是因为他们的任务应该只是检索有关对象的信息,而不是修改它。

你只需要尝试编译你的代码就可以看到它不起作用 - 来自 ideone.com here:

prog.cpp: In copy constructor 'Dog::Dog(const Dog&)':
prog.cpp:13:46: error: passing 'const Dog' as 'this' argument of 'std::string Dog::getName()' discards qualifiers [-fpermissive]
       Dog(const Dog& d) { m_name = d.getName(); m_age = d.getAge(); }
                                              ^
prog.cpp:13:66: error: passing 'const Dog' as 'this' argument of 'int Dog::getAge()' discards qualifiers [-fpermissive]
       Dog(const Dog& d) { m_name = d.getName(); m_age = d.getAge(); }
                                                                  ^

您可以通过 "get" 函数修复它 const:

string getName() const { return m_name; }
int getAge() const { return m_age; }

可以看到版本编译成功here

It can't.

问之前先试一下。