C++ - 方法和重载中的 const 关键字

标签 c++ overloading

为什么这个程序:

#include <iostream>
using namespace std;
class Base {
public:
  Base() { cout << "Costruttore Base" << endl; }
  virtual void foo(int) { cout << "Base::foo(int)" << endl; }
  virtual void bar(int) { cout << "Base::bar(int)" << endl; }
  virtual void bar(double) { cout << "Base::bar(double)" << endl; }
  virtual ~Base() { cout << "Distruttore Base" << endl; }
};
class Derived : public Base {
public:
  Derived() { cout << "Costruttore Derived" << endl; }
  void foo(int) { cout << "Derived::foo(int)" << endl; }
  void bar(int) const { cout << "Derived::bar(int)" << endl; }
  void bar(double) const { cout << "Derived::bar(double) const" << endl; }
  ~Derived() { cout << "Distruttore Derived" << endl; }
};
int main() {
  Derived derived;
  Base base;
  Base& base_ref = base;
  Base* base_ptr = &derived;
  Derived* derived_ptr = &derived;
  cout << "=== 1 ===" << endl;
  base_ptr->foo(12.0);
  base_ref.foo(7);
  base_ptr->bar(1.0);
  derived_ptr->bar(1.0);
  derived.bar(2);
  return 0;
}

在调用 base_ptr->bar(1.0); 中调用 Base::bar(double),而不是在 derived_ptr->bar(1.0 ); 被称为 Derived::bar(double) const

我知道这是关于 const 关键字的,但我不明白为什么编译器会选择不同的重载函数。

如果我删除 const 关键字,一切都会按预期工作,在这两种情况下都会调用 Derived::bar

最佳答案

那是因为const改变了函数的签名,所以它们是不同的。要么使基类和派生类都成为const,要么一个都不会覆盖另一个。

关于C++ - 方法和重载中的 const 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716636/

相关文章:

c++ - 没有参数特征名称的重载括号运算符

c++ - 左值引用和右值引用之间的重载决议

c++ - 迭代器拼接列表后存储了错误的值

c++ - 将 uint64_t 转换为 uint8_t[8]

c++ - 为什么 SFINAE 不选择 const-reference-taking 重载?

c# - 可选参数和方法重载

c++ - 如何重载 << 运算符以使用模板函数将元素添加到 vector 中? (c++)

c++ - 如何将整数数组相乘得到一个数字?

c# - Powershell 为 Func<T> 而不是 Action<T> 创建脚本 block

function - dart 是否支持运算符重载