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 看看
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++ 底层, 引用 也是指针

浙公网安备 33010602011771号