gpt4 book ai didi

c++ - 在这种情况下是私有(private)的吗?试图重载 << 运算符

转载 作者:行者123 更新时间:2023-12-02 09:53:54 25 4
gpt4 key购买 nike

#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 在此上下文中是私有(private)的,但我没有将其设为私有(private)。我上面带有格式化输出的 std::stream &operator 是我遇到问题的那个。

最佳答案

类的默认访问说明符是 private ,这就是为什么你的namepublic 之外定义的成员说明符是一个私有(private)变量。

更多 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.



如您所见, struct另一方面有一个默认 public这是两者之间的唯一区别。

关于c++ - 在这种情况下是私有(private)的吗?试图重载 << 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61987838/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com