c++ - 在这种情况下是私有的吗?试图重载 << 运算符
问题描述
#include <cctype>
#include <deque>
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
#include <list>
#include <limits>
class Song {
friend std::ostream &os(std::ostream &os, const Song &s);
std::string name;
std::string artist;
int rating;
public:
Song() = default;
Song(std::string name, std::string artist, int rating)
: name{name}, artist{artist}, rating{rating} {}
std::string get_name() const {
return name;
}
std::string get_artist() const {
return artist;
}
int get_rating() const {
return rating;
}
bool operator<(const Song &rhs) const {
return this->name < rhs.name;
}
bool operator==(const Song &rhs) const {
return this->name == rhs.name;
}
};
std::ostream &operator<<(std::ostream &os, const Song &s){
os << std::setw(20) << std::left << s.name
<< std::setw(30) << std::left << s.artist
<< std::setw(2) << std::left << s.rating;
return os;
}
我收到错误 Song::name 在此上下文中是私有的,但我没有将其设为私有。我上面带有格式化输出的 std::stream &operator 是我遇到的问题。
解决方案
The default access specifier for classes is private
, that is why your name
member defined outside the public
specifier is a private variable.
More here:
A class defined with the keyword class has private access for its members and its base classes by default. A class defined with the keyword struct has public access for its members and its base classes by default. A union has public access for its members by default.
As you can see, a struct
on the other hand has a default public
which is the only difference between the two.
推荐阅读
- ruby - 控制器和交互器错误处理的最佳实践
- amazon-web-services - 增加索引是否会导致 AWS RDS 的写入 IOPS 上升?
- c++ - 如何以更有效的方式判断枚举类值是否在枚举类的指定范围内?
- java - 如何在 Spring Data JPA 中编写以下 SQL 查询?
- android - RecyclerView 在第一个 (4 - 5) 滚动时滞后
- android - PocketSphinx:如何识别关键字后跟动态词?
- java - 从服务中获取价值的启动画面
- angular - 当我选择单选按钮时,Angular-Material 单选按钮数据未绑定
- c# - c# razor generator 编译错误与 NancyFx 项目
- vue.js - Vue Draggable with touch - drop 不会触发