<分区>
我想创建卡片类,其中有方法打印和重载运算符(卡片比较)
这是我的代码:
#include <iostream>
#include <vector>
#include <string>
#include <stdexcept>
using namespace std;
enum Face {Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen,King, Ace};
enum Suit {Hearts,Clubs,Diamonds,Spades};
class Card{
private:
Face face;
Suit suit;
public:
Card();
Card(const Face face,const Suit suit);
void print();
friend bool operator>(Card& lhs,Card&rhs);
friend bool operator==(Card& lhs,Card& rhs);
friend bool operator!=(Card& lhs,Card& rhs);
friend bool operator<(Card& lhs,Card& rhs);
};
const char* to_string_1(const Face value)
{
const char* LUT[] = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace" };
return LUT[value];
}
const char* to_string_2(const Suit value)
{
const char* LUT[] = {"Hearts", "Clubs", "Diamonds", "Spades" };
return LUT[value];
}
Card::Card(){
}
Card::Card(Face rank_card,Suit suit_card){
face = rank_card;
suit = suit_card;
}
void Card::print(){
cout << to_string_1(face) << " " << to_string_2(suit);
}
bool operator==(const Card& lhs, const Card& rhs){
if(lhs.face == rhs.face && lhs.suit == rhs.suit) return true;
return false;
}
bool operator!=(const Card& lhs,const Card& rhs){
if(lhs.face != rhs.face || lhs.suit != rhs.suit) return true;
return false;
}
bool operator>(const Card& lhs,const Card& rhs){
if(lhs.face > rhs.face && lhs.suit > rhs.suit) return true;
if(lhs.face > rhs.face && lhs.suit == rhs.suit) return true;
if(lhs.face == rhs.face && lhs.suit > rhs.suit) return true;
return false;
}
bool operator<(const Card& lhs,const Card& rhs){
if(lhs.face < rhs.face && lhs.suit < rhs.suit) return true;
if(lhs.face < rhs.face && lhs.suit == rhs.suit) return true;
if(lhs.face == rhs.face && lhs.suit < rhs.suit) return true;
return false;
}
int main(){
Card c_1(Two,Clubs);
Card c_2(Five,Diamonds);
c_2.print();
}
问题是,编译器向我抛出错误,例如:
12:10: 错误:'Face Card::face' 是私有(private)的 58:24:错误:在此上下文中 13:10: 错误:'Suit Card::suit' 是私有(private)的 58:36:错误:在此上下文中
但我将运算符定义为“友元”函数。为什么程序仍然报错?