简体   繁体   English

C ++继承函数覆盖

[英]C++ inheritance function overriding

I have a question (part of my homework) which im unsure of the code's behavior. 我有一个问题(我的家庭作业的一部分),我不确定代码的行为。

I got a class Father , which owns a function "A", function "A" prints "Hello Father". 我有一个class Father ,它拥有一个功能“A”,功能“A”打印“你好父亲”。
I got a second class -> class son:public Father , which does not owns function "A". 我得到了第二堂课 - > class son:public Father ,不拥有“A”功能。
I got a third class -> class grandson:public son , which owns function "A" which prints "Hello grandson". 我得到了第三类 - > class grandson:public son ,拥有打印“你好孙子”的功能“A”。

Function "A" is not virtual. 功能“A”不是虚拟的。 Please ignore compiling errors, I didnt want to put here a 80 lines of code. 请忽略编译错误,我不想在这里放80行代码。

I have another function : 我有另一个功能:

void justPrint(const son& a) {
   a.A;
}

Now, what will be printed in the following call : 现在,将在以下电话中打印什么:

grandson jeff;
justPrint(jeff);

I'm a bit confused, son dont have the print function (A), so he suppose to call to Father::A (son is a father..) 我有点困惑,儿子没有打印功能(A),所以他想打电话给父亲:: A(儿子是父亲......)
but, we send jeff (grandson) to the function which recieves son.. and grandson is a son.. 但是,我们把杰夫(孙子)送到接收儿子的功能..孙子是儿子..

I think that it will print 我认为它会打印出来

"Hello Father" “你好父亲”

But i'm so confused... Will appericiate any help and explenation.. 但我很困惑......请知道任何帮助和言论。

Second thing, What will happen if i will make the following call : 第二件事,如果我将进行以下调用将会发生什么:

justPrint(1);

I try to make a short code to solve your problem, but I don't have it (using "g++ test.cpp -fpermissive" to compile) 我尝试制作一个简短的代码来解决你的问题,但我没有它(使用“g ++ test.cpp -fpermissive”来编译)

#include <iostream>

using namespace std;

class Father
{
    public:
    void A(){
        cout<<"Hello Father"<<endl;
    }
};

class Son : public Father
{
};

class GrandSon : public Son
{
    public:
    void A()
    {
        cout<<"Hello GrandSon"<<endl;
    }
};

void justPrint(const Son& a)
{
    a.A();
}

int main(int argc, char* argv[])
{
    GrandSon jeff;
    justPrint(jeff);
    return 0;
}

Maybe you have put A in private? 也许你把A私有?


Output: Hello Father 输出:你好父亲

void justPrint(const son& a) {
   a.A;
}

justPrint(1); if Class son contains single argument constructor with int as i/p.It will call that .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM