effective C++ 20#有感

看看下面代码:

class base{
public:
    base(){
        name = "my name is base" ;
    }
    string name ;
    virtual void show(){
        cout << "it's base"<<endl;
    }
};
class A:public base{
public:
    A(){
        name = "my name is A";
    }
    string name ;
     void show(){
        cout << "it's A test"<<endl;
    }
};
void fun(base* w){
    cout << w->name <<endl;
    w->show();
}
int main(){
    A* pa= new A();
    fun(pa);
    return 0;
}

这个大家见得很多,结果很自然是:

my name is base

it's A test

再来改一点点(下面只改到fun和main,其它不变)

void fun(base wb){
    cout << wb.name <<endl;
    wb.show();
}
int main(){
    A aa;
    fun(aa);
    return 0;
}

不知道结果会不会让大家有点意外,反正我有点

my name is base

it's base

这里的virtual 不起作用了哦

再来看看下面一段代码:

void fun(base &wb){
    cout << wb.name <<endl;
    wb.show();
}
int main(){
    A aa;
    fun(aa);
    return 0;
}

结果又变回去了

my name is base

it's A test

加个const 看看
effective C++ 20#有感effective C++ 20#有感View Code

1 class base{
 2 public:
 3     base(){
 4         name = "my name is base" ;
 5     }
 6     string name ;
 7     virtual void show() const {
 8         cout << "it's base"<<endl;
 9     }
10 };
11 class A:public base{
12 public:
13     A(){
14         name = "my name is A";
15     }
16     string name ;
17      void show() const {
18         cout << "it's A test"<<endl;
19     }
20 };
21 void fun(const base &wb){
22     cout << wb.name <<endl;
23     wb.show();
24 }
25 int main(){
26     A aa;
27     fun(aa);
28     return 0;
29 }

运行结果:(与上面一样的)

my name is base

it's A test

这里还要注意一下, void show() const{} 与void show(){} 是两个完全不同的函数

理解:

1、传入指针的话,指的是同一对象 ,而 pass to value 也会是复制

2、其实在C++ 底层, 引用 也是指针
原文链接: https://www.cnblogs.com/raowarrior/archive/2012/09/06/2673220.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/61979

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 上午10:13
下一篇 2023年2月9日 上午10:14

相关推荐