结合例子说明类对象作为形参的解释。
具体解释见例子中的注释部分以及结尾的总结部分。
#include
using namespace std;
class A {
public:
A() {
cout<<"class A
construction"<<endl;
};
~A(){
cout<<"class A
destruction"<<endl;
};
void func_classrefobj_as_formalpara(A &a){
cout<<"class A
func_classrefobj_as_formalpara(A &a)
"<<endl;
}
void func(A a){
cout<<"class A func(A a)
"<<endl;
}
};
void main()
{
A a;
a.func(a); //类对象直接作为形式参数进行传递
a.func_classrefobj_as_formalpara(a);//类对象以引用形式作为参数进行传递时,类对象是通过内存拷贝传递的,修改形参的同时会影响实参对象。
cin.get();//cin.get() 表示从键盘读入一个字符
}
#include
using namespace std;
class CTest
{
public:
CTest(){cout <<"CTest
construction"<<endl;}
CTest(CTest &a){
cout<<"CTest copy
construction"<<endl;
};
~CTest(){cout <<"CTest
destruction"<<endl;}
};
class A
{
public:
A(CTest s){cout <<"A
construction"<<endl;}
//当使用此函数时,调用test的默认拷贝构造函数
~A(){cout <<"A
destruction"<<endl;}
};
void main()
{
CTest a;
//A c(a);//创建对象(构造函数含有类对象参数)
A *b=new A(a);
delete b;
}
#include
using namespace std;
class Cat
{
private:
int age;
public:
Cat()
{
age=0;
}
void ChangeAge(int itage)
{
age=itage;
}
int GetAge()const
{
return age;
}
void Change(Cat c) ;
};
void Cat::Change(Cat
c)
//按值传递
{
int a;
cout<<"输入猫咪的年龄:";
cin>>a;
c.ChangeAge(a);
}
int main()
{
Cat Kitty;
Kitty.Change(Kitty);
cout << "Kitty is
"<<Kitty.GetAge()<<"
years old" << endl;
return 0;
}
结果如下:
输入猫咪的年龄:9
Kitty is 0 years old
#include
using namespace std;
class Cat
{
private:
int age;
public:
Cat()
{
age=0;
}
void ChangeAge(int itage)
{
age=itage;
}
int GetAge()const
{
return age;
}
void Change(Cat &c);
};
void Cat::Change(Cat
&c)
//按地址传递
{
int a;
cout<<"输入猫咪的年龄:";
cin>>a;
c.ChangeAge(a);
}
int main()
{
Cat Kitty;
Kitty.Change(Kitty);
cout << "Kitty is
"<<Kitty.GetAge()<<"
years old" << endl;
return 0;
}
结果如下:
输入猫咪的年龄:7
Kitty is 7 years old
上述结果说明:类对象直接作为形参,进行的是值传递(类对象是被存放在栈上的,不影响实参的数据)。类对象以引用形式作为形参,进行的是地址传递(类对象是通过内存拷贝传递的,修改形参的同时会影响实参对象)。
加载中,请稍候......