C++ 内联运算符重载,引用当前对象
C++ Inline Operator Overloading, refer to current object
所以我最近才开始使用 "Inline operator overloading" 或其他名称......
无论如何!!我怎样才能引用我从中调用函数的对象。这是感兴趣的代码:
class PlayingCard
{
private:
enum Suit {diamond, hearts, spades, clubs};
Suit suit;
enum Color {red, black};
Color color;
int value = -1;
public:
//Inline stuff
//make card the same as c1
inline operator=(const PlayingCard &c1) {
suit = c1.suit;
color = c1.color;
value = c1.value;
return true;
}
inline operator%(PlayingCard &c1) {
PlayingCard copy1;
copy1 = c1;
c1 = this;
this = copy1;
return true;
}
如您所见,我有 class PlayingCard。第一个内联运算符正常工作。如果我有 2 个 PlayingCard:c1 和 c2,并且定义了 c2 的私有值,则 c1 = c2 使 c1 的私有值等于 c2。
第二个内联函数旨在通过执行 c1 % c2 来交换 c1 和 c2 之间的值。如代码所示,我希望使用 "this" 来引用 c1,但它不起作用。有没有办法在这个函数中引用c1?
我知道在此期间我会使用一些变通方法,但我宁愿使用我原来的方法,我觉得它对将来的使用也有帮助。
C++ 中的运算符重载仅允许您执行该语言提供的某些操作。你不能自己编。所以你不能为 <->
做一个
(对于 assemble 个别 <
、-
和 >
运算符可能有一些复杂的方法。但即使那是可能的,它可能不值得付出努力,而且很可能还会允许意外的奇怪用法。)
在 C++ 中没有像 <->
这样的运算符(您后来在更新的问题中更改为 %
)。看来你要定义一个成员函数swap
。但是在任何情况下你都不能交换常量对象。所以函数的参数应该是非常量引用
在 class 定义中定义的成员函数默认具有内联函数说明符。所以不需要明确指定。
赋值运算符应该return对赋值对象的引用。
给你。
PlayingCard & operator =( const PlayingCard &c1 )
{
if ( this != &c1 )
{
suit = c1.suit;
color = c1.color;
value = c1.value;
}
return *this;
}
void swap( PlayingCard &c1 )
{
if ( this != &c1 )
{
std::swap( suit, c1.suit );
std::swap( color, c1.color );
std::swap( value, c1.value );
}
}
所以我最近才开始使用 "Inline operator overloading" 或其他名称...... 无论如何!!我怎样才能引用我从中调用函数的对象。这是感兴趣的代码:
class PlayingCard
{
private:
enum Suit {diamond, hearts, spades, clubs};
Suit suit;
enum Color {red, black};
Color color;
int value = -1;
public:
//Inline stuff
//make card the same as c1
inline operator=(const PlayingCard &c1) {
suit = c1.suit;
color = c1.color;
value = c1.value;
return true;
}
inline operator%(PlayingCard &c1) {
PlayingCard copy1;
copy1 = c1;
c1 = this;
this = copy1;
return true;
}
如您所见,我有 class PlayingCard。第一个内联运算符正常工作。如果我有 2 个 PlayingCard:c1 和 c2,并且定义了 c2 的私有值,则 c1 = c2 使 c1 的私有值等于 c2。
第二个内联函数旨在通过执行 c1 % c2 来交换 c1 和 c2 之间的值。如代码所示,我希望使用 "this" 来引用 c1,但它不起作用。有没有办法在这个函数中引用c1?
我知道在此期间我会使用一些变通方法,但我宁愿使用我原来的方法,我觉得它对将来的使用也有帮助。
C++ 中的运算符重载仅允许您执行该语言提供的某些操作。你不能自己编。所以你不能为 <->
(对于 assemble 个别 <
、-
和 >
运算符可能有一些复杂的方法。但即使那是可能的,它可能不值得付出努力,而且很可能还会允许意外的奇怪用法。)
在 C++ 中没有像 <->
这样的运算符(您后来在更新的问题中更改为 %
)。看来你要定义一个成员函数swap
。但是在任何情况下你都不能交换常量对象。所以函数的参数应该是非常量引用
在 class 定义中定义的成员函数默认具有内联函数说明符。所以不需要明确指定。
赋值运算符应该return对赋值对象的引用。
给你。
PlayingCard & operator =( const PlayingCard &c1 )
{
if ( this != &c1 )
{
suit = c1.suit;
color = c1.color;
value = c1.value;
}
return *this;
}
void swap( PlayingCard &c1 )
{
if ( this != &c1 )
{
std::swap( suit, c1.suit );
std::swap( color, c1.color );
std::swap( value, c1.value );
}
}