首页 > 解决方案 > 在这种情况下是私有的吗?试图重载 << 运算符

问题描述

#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 是我遇到的问题。

标签: c++c++11

解决方案


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.


推荐阅读