现在的位置: 首页 > 综合 > 正文

在C++的虚继承中要注意的一个传值问题

2013年02月04日 ⁄ 综合 ⁄ 共 763字 ⁄ 字号 评论关闭

// tea.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <iostream>

using namespace std;

class justtest1

{

public:

       virtual void display()

       {

              cout<<"justtest1"<<endl;

       }

};

class justtest2:public justtest1

{

public:

       virtual void display()

       {

              cout<<"justtest2"<<endl;

       }

};

 

void displayclassname(justtest1 test)

{

       test.display  ();

}

 

void displayclassname2 (justtest1& test)

{

  test.display  ();

}

int main(int argc, char* argv[])

{

       justtest1 a;

       justtest2 b;

       a.display  ();

       b.display  ();

    displayclassname(b); //输出结果是test1,

                                  //在不使用引用的情况下会发生slicing(切割)

    displayclassname2(b);//输出结果是test2

                                     //使用了reference,情况没改变

       return 0;

}

 

以后C++中一律使用引用传值

抱歉!评论已关闭.