在基类中定义了友元函数,在派生类继承了基类中的友元函数吗?
用例子来说明:
- #include <iostream>
-
using namespace std;
-
class Increase
-
{
-
public:
-
Increase(int x):value(x){}
-
friend Increase& operator++(Increase&); //前增量
-
friend Increase operator++(Increase&, int); //后增量
-
void display(){ cout << "the value of Increase is " << value <<endl;}
-
protected:
-
int value;
-
};
-
Increase& operator++(Increase& a)
-
{
-
a.value++;
-
return a;
-
}
-
Increase operator++(Increase& a, int)
-
{
-
Increase temp(a);
-
a.value++;
-
return temp;
-
}
- class Derived: public Increase
- {
- public:
- Derived(int x):Increase(x){}
- };
-
int main()
-
{
-
Derived der(10);
-
der.display();
-
(++der).display();
-
return 0;
-
}
运行的结果为:
the value of Increase is 10
the value of Increase is 11
从这个结果来看:似乎可以得出“派生类继承了基类的友元函数”的结论。但是,我们将代码稍微
修改一下:
- #include <iostream>
-
using namespace std;
-
class Increase
-
{
-
public:
-
Increase(int x):value(x){}
-
friend Increase& operator++(Increase&); //前增量
-
friend Increase operator++(Increase&, int); //后增量
-
void display(){ cout << "the value of Increase is " << value <<endl;}
-
protected:
-
int value;
-
};
-
Increase& operator++(Increase& a)
-
{
-
a.value++;
-
return a;
-
}
-
Increase operator++(Increase& a, int)
-
{
-
Increase temp(a);
-
a.value++;
-
return temp;
-
}
- class Derived: public Increase
- {
- public:
- Derived(int x):Increase(x){}
- friend Derived& operator++(Derived&); //前增量
- void display(){ cout << "the value of Derived is " << value <<endl; }
- };
- Derived& operator++(Derived& a)
- {
- a.value++;
- a.value++;
- }
-
int main()
-
{
-
Derived der(10);
-
der.display();
-
(++der).display();
-
return 0;
-
}
运行结果为:
the value of Derived is 10
the value of Derived is 12
可以看出,派生类根本没有继承基类的友元函数,但是我们可以将派生类的对象传递给基类的友元函数,
他会自动转换成基类的对象,使得基类的友元函数也可以调用成功。
阅读(1509) | 评论(0) | 转发(0) |