由于 c2 是 c1 的子节点,因此它继承了函数 getHi()
首先,您应该说c2
“派生自”,或“是的派生类”,或“继承(在您的情况下是私下)从” c1
。此外,“继承”是正确的动词。
但是,如果你这样做会发生什么?
在这种情况下,无法执行强制转换,因为您从c1
. 更改c2
如下定义,您将看到两个调用以getHi()
完全相同的方式工作(在本例中):
class c2 : public c1 { };
// ^^^^^^
// This means that public members of c1 will become
// public members of c2 as well. If you specify nothing,
// public members of c1 will become private members of
// c2
请注意,您还缺少类定义后的分号,最重要的是,和public
定义中的访问修饰符:没有它们,构造函数将是,因此您将根本无法实例化这些类:c1
c2
private
class c1
{
public: // <== Don't forget this!
c1() {} // Btw, why this? It does nothing
double getHi() { return _hi; }
private:
double _hi = 2;
}; // <== Don't forget this!
class c2 : public c1
// ^^^^^^ Don'f forget this!
{
public: // <== Don't forget this!
c2() {} // Btw, why this? It does nothing
}; // <== Don't forget this!
int main()
{
c2* b = new c2();
b->getHi(); // Compiles, calls c1::getHi();
((c1*)b)->getHi(); // Compiles, calls c1::getHi();
}