Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/150.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 子类到基类的转换问题_C++_Virtual - Fatal编程技术网

C++ 子类到基类的转换问题

C++ 子类到基类的转换问题,c++,virtual,C++,Virtual,我已经声明了一个带有虚拟打印函数的超类,子类继承了超类。我已经创建了一个Child类的实例,并以两种不同的方式分配给Super类 #include <iostream> using namespace std; class Super { public: Super(){} virtual void print() { cout << "Super class is printing " << endl; } };

我已经声明了一个带有虚拟打印函数的超类,子类继承了超类。我已经创建了一个Child类的实例,并以两种不同的方式分配给Super类

#include <iostream>

using namespace std;

class Super
{
public:
    Super(){}
    virtual void print()
    {
    cout << "Super class is printing " << endl;
    }
};

class Child: public Super
{
public:
    Child(){}
    void print()
    {
        cout << "Child class printing" << endl;
    }
};

int main()
{
    Child c;
    Super s = c;
    Super &ss = c;
    s.print(); //prints "Super Class is printing
    ss.print(); //prints "Child Class is printing
    return 0;
}
#包括
使用名称空间std;
超级班
{
公众:
超级(){}
虚拟空打印()
{
cout动态和静态类型的
s
Super
,但是
c
中的赋值从
c
内部复制
Super
子对象,
s
始终表现为
Super

但是,
ss
的静态类型为
Super
,但其动态类型取决于其初始化,在本例中为
Child
,因此虚拟分派会相应地进行

这种现象称为对象切片问题: 如果您获取一个超类并为其指定子类的值,则仅复制属于该超类的成员(默认赋值运算符行为)

考虑以下几点:

#include <iostream>

using namespace std;

class Super {
public:
   int a;
   Super(): a(0) { }
   Super(int _a): a(_a) { }
   virtual void dump() {
        cout << "A is : " << a << std::endl;
   }
};

class Child: public Super {
public: 
   int b;

   Child(int _a, int _b): b(_b), Super(_a) { } 
   virtual void dump() {
        Super::dump();
        cout << "B is : " << b << std::endl;
   }

};

int main() {
    Child c(5, 10);
    Super s;
    s.dump();  // A is 0
    s = c;
    s.dump();  // A is 5 (but there is no B in s 
               // so calling Child::dump would be nonsensical
}

   c.print();
" 要更清楚地看到这一点,请考虑下面的片段:

int foo;
int& bar = foo;

// bar is now a reference to foo so the following will sets foo to 67
bar = 67;
std::cout << foo <<std::endl;
intfoo;
int&bar=foo;
//bar现在是对foo的引用,因此下面将foo设置为67
bar=67;

std::看不出有点迂腐:“引用变量是分配给它的任何东西的同义词”不,是指初始化它所用的任何东西。它与实际的赋值无关,即使它可能使用
=
,就像在您的示例中一样。初始化引用的一些其他方法:
int&bar{foo};
(C++11)和
int&bar(foo)
。对于创建引用的过程,一个更好的术语是绑定,然后我们可以讨论它绑定到的对象。@DyP细微差别:-)我来解决这个问题。
int foo;
int& bar = foo;

// bar is now a reference to foo so the following will sets foo to 67
bar = 67;
std::cout << foo <<std::endl;