函数调用父类方法而不是子? [英] Function calls parent class method instead of child?

查看:126
本文介绍了函数调用父类方法而不是子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这里发生了什么,我不知道。请帮助。

I try to figure out what is happening here, and I dont know. Please help.

class A
{
protected:
    string name;
public:
    A(string a) {name = a;}
    virtual string getName() {return "A name: " + name;}
};


class B: public A
{
public:
    using A::A;
    string getName() {return "B name: " + name;}
};


void print_name(A obj)
{
    cout << obj.getName() << endl;
}


int main()
{

    A a("a");
    B b("b");

    print_name(a);
    // "A name: a"

    print_name(b);
    // "A name: b"  why not "B name: b"????

    return 0;
}

为什么第二次调用print_name给A名:b。这意味着getName()从A类被执行,但它应该是从B类?我做了虚方法。

Why second call to print_name(b); give "A name: b". It means that getName() from A class is executed, but it should be from B class? I made method virtual.

推荐答案

说你有: class B:public int int 的任何是否为此类的实例?显然不是。

Say you had: class B : public int. Would there be any value of an int that's an instance of this class? Clearly not.

现在考虑:

class B: public A
...
void print_name(A obj)

$ c> print_name 函数通过值获取 A 。是 B 的实例 A 是否有

The print_name function takes an A by value. Is there any value of an A that is an instance of B? Again, no.

也许你想要的:

void print_name(A& obj)

引用 A 可以是 B

这篇关于函数调用父类方法而不是子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆