为什么我不能将朋友函数声明为const
?
//Types.h
#pragma once
#include <string>
#include <ostream>
class Player
{
public:
//constructors
Player();
Player(const std::string&, unsigned short);
//operator overload
friend std::ostream& operator<<(std::ostream&, const Player&);
// (I can't declare it as const)
//getter
const std::string& get_id() const;
private:
std::string id;
unsigned short lvl;
};
//Types.cpp
#include "Types.h"
#include <iostream>
#include <iomanip>
/*other definitions*/
std::ostream& operator<<(std::ostream& out, const Player& print)
{
std::cout << "Player: " << std::setw(6) << print.id << " | " << "Level: " << print.lvl;
return out;
}
我的意思是,如果我想在常量变量或常量函数中调用operator<<
,即使operator<<
不是constant,即使它在内部没有变化,也会出现错误。课。
但是operator<<
不是成员-它是一个自由函数。因此,没有没有修改的基础对象。
int myFunc() const {
return 3;
}