小编nap*_*ets的帖子

用C++切片我错了?

我读到了C++中的切片问题,我尝试了一些例子(我来自Java背景).不幸的是,我不明白一些行为.目前,我被困在这个例子中(来自Efficent C++第三版的替代例子).任何人都可以帮我理解吗?

我父母的简单类:

class Parent
{
public:

    Parent(int type) { _type = type; }

    virtual std::string getName() { return "Parent"; }

    int getType() { return _type; }

private:

    int _type;
};
Run Code Online (Sandbox Code Playgroud)

我简单的一个孩子:

class Child : public Parent
{

public:

    Child(void) : Parent(2) {};

    virtual std::string getName() { return "Child"; }
    std::string extraString() { return "Child extra string"; }
};
Run Code Online (Sandbox Code Playgroud)

主要的:

void printNames(Parent p)
{
    std::cout << "Name: " << p.getName() << std::endl;

    if (p.getType() == 2)
    {
        Child & c …
Run Code Online (Sandbox Code Playgroud)

c++ inheritance object-slicing

4
推荐指数
1
解决办法
210
查看次数

标签 统计

c++ ×1

inheritance ×1

object-slicing ×1