gpt4 book ai didi

c++ - 成员是私有(private)的,C++ 中的运算符重载

转载 作者:行者123 更新时间:2023-11-28 04:53:44 25 4
gpt4 key购买 nike

<分区>

我想创建卡片类,其中有方法打印和重载运算符(卡片比较)

这是我的代码:

#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:错误:在此上下文中

但我将运算符定义为“友元”函数。为什么程序仍然报错?

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