假设我们有 2 个类:
class DataStructure {
public:
DataStructure &operator=(const DataStructure &);
friend const DataStructure &operator+(int, const DataStructure &);
//...
};
class Array : public DataStructure {
public:
Array &operator=(const DataStructure &);
friend const Array &operator+(int, const Array &);
//...
};
我们希望Array::operator=
and的 freind 和and的Array
freindoperator+
做同样的事情,除了他们应该返回,而不是, 。我需要用几十种方法来做,那么有没有比下面更简单的方法来实现它?DataStructure::operator=
DataStructure
operator+
Array &
const Array &
DataStructure &
const DataStructure &
Array &Array::operator=(const DataStructure &other) {
return (Array &)DataStructure::operator=(other);
}
const Array &operator+(int x, const Array &other) {
return (const Array &)(x + (DataStructure)other);
}
编辑:我想出了另一个想法,虽然这是一个非常糟糕的想法:
class Array;
class DataStructure {
public:
//...
operator Array &() const;
};
//...
DataStructure::operator Array &() const {
return (Array &)*this;
}
这种方式会在需要时DataStructure
隐式转换为Array
,尽管它仍然无法正确处理两者DataStructure
和Array
都是合法但做不同事情的情况,如下例所示:
//in class DataStructure:
public:
friend ostream &operator<<(ostream &os,const DataStructure &)
{ os << "DataStructure" << endl; return os;}
//in class Array:
public:
friend ostream &operator<<(ostream &os,const Array &)
{ os << "Array" << endl; return os;}
//...
int main() {
Array x;
cout << 1 + x << endl;
// output: "DataStructure" instead of "Array"
return 0;
}
谢谢!