重写运算符在 C++ 中无效
override operator invalid in c++
我在代码中编写了两个覆盖运算符(<<用于 Suit 和 <<用于 Card),但有时似乎不起作用。我尝试在卡的覆盖运算符<<中两次调用 Suit 的操作员。第二个不起作用,为什么?
class Card{
public:
enum Suit{CLUBS, SPADES, HEARTS, DIAMOND};
Card(int v, Suit s): value(v), suit(s){};
int getValue()const{return value;}
Suit getSuit()const{return suit;}
private:
int value;
Suit suit;
};
ostream& operator<< (ostream& out, Card::Suit& s){
switch (s) {
case 0:
out << "CLUBS";
break;
case 1:
out << "SPADES";
break;
case 2:
out << "HEARTS";
break;
default:
out << "DIAMOND";
break;
}
return out;
}
ostream& operator<< (ostream& out, Card& c){
Card:: Suit s = c.getSuit();
out << s << endl; //here it output what I want: SPADES
out << "Card with Suit " << c.getSuit() << " Value " << c.getValue() << endl;
return out; //here the c.getSuit() output 1 instead of SPADES, why?()
}
int main(){
Card* c = new Card(1, Card::SPADES);
cout << *c;
return 1;
}
尝试将 suit 更改为枚举类 - 然后它将被强类型化而不是转换为 int。
...
enum class Suit {CLUBS,SPADES,HEARTS,DIAMONDS};
...
ostream& operator<<(ostream& os, Card::Suit& s) {
switch (s) {
case Card::Suit::CLUBS:
os << "Clubs";
break;
...
然后在您的其他代码中,cout << c.getSuit() << endl
不会隐式转换为 int 并输出数字。
相关文章:
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 无法访问嵌套类.类的使用无效
- 如果用户输入无效,如何使用字符串变量-C++重复输入命令
- 如何解决错误:SCIP C++中的 SCIP 阶段无效 <10>
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- FFMPEG配置文件级别id大小无效
- 错误:从"int"到枚举c++的转换无效
- 如何修复此错误:className::className的无效使用
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- C++-模板嵌套类的引用初始化无效
- 错误:无效的预处理指令 #i 的意思是 #if?
- 多维数组 C++ 中数组下标的类型"int[int]"无效
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- 从 'int' 到 'int*' CPP 的转换无效
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 由于无效的 ValidateRgn() 子窗口不会收到WM_PAINT消息
- C++ PTHREADS - 无效转换无效*(*)()到无效*(*)(无效*)
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 数组下标的类型"float*[float]"无效
- 修改 std::vector 会使迭代器无效吗?