Làm thế nào để xác định bạn bè cho các lớp học riêng?bạn bè cho lớp riêng
#include <iostream>
class Base_t{
private:
struct Priv_t{
friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj);
} p;
friend std::ostream & operator<<(std::ostream &os, const Base_t& obj);
};
std::ostream & operator<<(std::ostream &os, const Base_t& obj) {
return os << "base: " << obj.p;
}
std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
return os << "priv";
}
int main() {
Base_t b;
std::cout << b << std::endl;
}
lỗi:
:!make t17 |& tee /tmp/vB5G5ID/54
g++ t17.cpp -o t17
t17.cpp: In function 'std::ostream& operator<<(std::ostream&, const Base_t::Priv_t&)':
t17.cpp:5:16: error: 'struct Base_t::Priv_t' is private
struct Priv_t{
^
t17.cpp:15:59: error: within this context
std::ostream & operator<<(std::ostream &os, const Base_t::Priv_t& obj) {
^
make: *** [t17] Error 1
shell returned 2
Nó hoạt động khi tôi xác định người bạn trực tiếp trong Priv_t
friend std::ostream & operator<<(std::ostream &os, const Priv_t& obj) { return os << "priv"; }
Làm thế nào để làm điều đó bên ngoài định nghĩa lớp/struct?
Bài tiếp theo của mã mà không có số dòng, xin vui lòng! –
@ DieterLàm xong. – name