【问题标题】:C++ declaring a const function in header and implementing it in .cppC++ 在标头中声明一个 const 函数并在 .cpp 中实现它
【发布时间】:2026-02-05 23:05:02
【问题描述】:

我有以下标题:

#include <string>

using namespace std;

enum COLOR {Green, Blue, White, Black, Brown};


class Animal{
    private:
    string _name;
    COLOR _color;

    public:
    Animal();
    ~Animal();
    void speak() const;
    void move() const;
} ;

以及以下 .cpp 实现:

#include <iostream>
#include <string>
#include "Animal.h"
Animal::Animal(): _name("unknown")
    {
        cout << "constructing Animal object" << endl;
    };
Animal::~Animal()
    {
        cout << "destructing Animal object" << endl;
    }
void Animal::speak()
    {
        cout << "Animal speaks" << endl;
    }
void Animal:: move(){};

但是,speak() 和 move() 函数给我一个错误:“no declaration matches Animal::speak()”。如果我删除声明末尾的“const”,则编译没有问题。 如何在 .cpp 文件中正确实现 const 函数?

【问题讨论】:

  • 在实现中将 const 放在void Animal::move() const{} 后面
  • @infinitezero 请把它作为答案,以便我接受!
  • 我认为这个问题会被关闭。但是其他人已经给出了答案。
  • 您应该考虑将定义拆分为一般的 cpp 文件,尤其是对于小型函数。只要您没有使用 LTO 进行编译,如果您在头文件中没有实现,您的代码通常会优化得更少!
  • 不!反之!将所有内容放在标题中,尤其是在方法很小的情况下。

标签: c++ constants header-files declaration


【解决方案1】:

您忘记在实现中输入const

将您的代码更改为:

void Animal::speak() const
{
    cout << "Animal speaks" << endl;
}
void Animal::move() const {};

【讨论】: