https://blog.csdn.net/kevin_zhao_zl/article/details/106937618(参考文章)
(1)作用域与成员函数
在基类和派生类中使用同一名字的成员函数,其行为与数据成员一样:在派生类作用域中派生类成员将屏蔽基类成员。即使函数原型不同,基类成员也会被屏蔽:
struct Base {
int memfcn();
};
struct Derived : Base {
int memfcn(int); // hides memfcn in the base
};
Derived d; Base b;
b.memfcn(); // calls Base::memfcn
d.memfcn(10); // calls Derived::memfcn
d.memfcn(); // error: memfcn with no arguments is hidden
d.Base::memfcn(); // ok: calls Base::memfcn
(2)通过基类调用被屏蔽的虚函数
通过基类类型的引用或指针调用函数时,编译器将在基类中查找该函数而忽略派生类:
class Base {
public:
virtual int fcn();
};
class D1 : public Base {
public:
// hides fcn in the base; this fcn is not virtual
int fcn(int); // parameter list differs from fcn in Base743
// D1 inherits definition of Base::fcn()
};
class D2 : public D1 {
public:
int fcn(int); // nonvirtual function hides D1::fcn(int)
int fcn(); // redefines virtual fcn from Base
};
Base bobj; D1 d1obj; D2 d2obj;
Base *bp1 = &bobj, *bp2 = &d1obj, *bp3 = &d2obj;
bp1->fcn(); // ok: virtual call, will call Base::fcnat run time
bp2->fcn(); // ok: virtual call, will call Base::fcnat run time
bp3->fcn(); // ok: virtual call, will call D2::fcnat run time
三个指针都是基类类型的指针,因此通过在 Base 中查找 fcn 来确定这三个调用,所以这些调用是合法的。另外,因为 fcn 是虚函数,所以编译器会生成代码,在运行时基于引用指针所绑定的对象的实际类型进行调用。在 bp2 的情况,基本对象是 D1 类的,D1 类没有重定义不接受实参的虚函数版本,通过bp2 的函数调用(在运行时)调用 Base 中定义的版本。
测试代码如下:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class A
{
public:
A() {}
~A() {}
virtual void func() const
{
std::cout << "A"<<std::endl;
}
virtual A* clone() const { return new A(*this); }
};
class B : public A
{
public:
B() {}
~B() {}
void func() const
{
std::cout << "B"<<std::endl;
}
virtual B* clone() const { return new B(*this); }
};
class sample
{
public:
sample() :p(0), use(1) {}
sample(const A& a) :p(a.clone()), use(1) {}
sample(const sample& i) :p(i.p), use(i.use) { use++; }
~sample() { decr_use(); }
sample& operator= (const sample& i)
{
use++;
decr_use();
p = i.p;
use = i.use;
return *this;
}
const A* operator->() const { if (p) return p;else return NULL; }
const A& operator*() const { if (p) return *p; }
private:
A* p;
std::size_t use;
void decr_use() { if (--use == 0) delete p; }
};
int main(void)
{
vector<sample> vec;
A a;
B b;
sample sample1(a);
sample sample2(b);
vec.push_back(sample1);
vec.push_back(sample2);
vector<sample>::iterator iter;
for (iter = vec.begin(); iter != vec.end(); iter++)
{
(*iter)->func();
}
return 0;
}
测试结果:
tekken@tekken:~/C++WS$ ./a.out
A
B
目标:732-750
完成:707-739-748
总体:707-777












网友评论