拷贝构造函数在哪些地方用,函数参数,函数返回值
2013-05-24 23:35
302 查看
首先看个程序。
输出结果是:
A
~A
~A
~A
请按任意键继续. . .
=================================================
关于函数参数和函数返回值的构造问题。
函数参数和返回值的构造都是调用的拷贝构造函数。
并且在函数返回时都需要析构。
输出结果:
A
B
A
B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
当把函数调用注释掉后,输出结果是:
A
B
A
B
~B
~A
~B
~A
请按任意键继续. . .
可见相比fun函数的调用,只是多了两次析构函数的调用而已。
PS:调用拷贝构造函数之前会自动调用父类的构造函数
A
B
A
B
A
construct B
A
construct B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
//多余调用的两次析构函数。是函数参数和返回值的析构。
//而函数参数和返回值都是拷贝构造函数完成构造的。
//参考文献:
//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html
#include <iostream> using namespace std; class A { public: A() { cout << "A"<<endl; } ~A() { cout << "~A"<<endl; } private: int x; }; void main() { A a; A b(a); A c(a); }
输出结果是:
A
~A
~A
~A
请按任意键继续. . .
=================================================
关于函数参数和函数返回值的构造问题。
函数参数和返回值的构造都是调用的拷贝构造函数。
并且在函数返回时都需要析构。
#include <iostream> using namespace std; class A { public: A() { cout << "A" <<endl; } ~A() { cout << "~A" <<endl; } private: string x,y; }; class B : public A { public: B() { cout << "B" <<endl; } ~B() { cout << "~B" <<endl; } private: string x1,y1; }; B fun(B b) { return b; } void main() { B a,b; b = fun(a); }
输出结果:
A
B
A
B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
当把函数调用注释掉后,输出结果是:
A
B
A
B
~B
~A
~B
~A
请按任意键继续. . .
可见相比fun函数的调用,只是多了两次析构函数的调用而已。
#include <iostream> using namespace std; class A { public: A() { cout << "A" <<endl; } A(const A &a) { cout << "construct A" <<endl; } ~A() { cout << "~A" <<endl; } private: string x,y; }; class B : public A { public: B() { cout << "B" <<endl; } B(const B &a) { cout << "construct B" <<endl; } ~B() { cout << "~B" <<endl; } private: string x1,y1; }; B fun(B b) { return b; } void main() { B a,b; b = fun(a); }
PS:调用拷贝构造函数之前会自动调用父类的构造函数
A
B
A
B
A
construct B
A
construct B
~B
~A
~B
~A
~B
~A
~B
~A
请按任意键继续. . .
//多余调用的两次析构函数。是函数参数和返回值的析构。
//而函数参数和返回值都是拷贝构造函数完成构造的。
//参考文献:
//http://www.cnblogs.com/renyuan/archive/2012/12/29/2839230.html
相关文章推荐
- C++函数参数,返回值,拷贝构造函数等
- 函数参数返回值 void 和 void *
- const 修饰函数参数,返回值,函数体,保护数据
- c++函数参数和返回值的规则
- C#多线程函数如何传参数和返回值
- 定义一个结构体变量(包含年月日),计算该日在本年中为第几天?要求写一个days函数。参数是此结构体类型的变量,返回值是整数。
- python装饰器:有参数的装饰器、不定长参数的装饰器、装饰有返回值的函数、通用的装饰器
- PHP_零基础学php_3PHP函数、传参函数、默认参数、函数返回值
- 基础知识—函数-函数参数及返回值
- C函数与汇编函数之间参数及返回值传递方法
- const 详解(修饰变量、输入参数、返回值、成员函数)
- 智能指针变量做函数参数的一个值得注意的地方
- 案例:Python将函数作为参数以及作为返回值
- 8086与ARM在函数调用中的参数传递与返回值存储
- C++中函数中参数和返回值都是用户定义类型(这里主要是类的情况时的分析)
- 创建一个数组, 实现函数init()初始化数组、 实现empty()清空数组、 实现reverse()函数完成数组元素的逆置。 要求:自己设计函数的参数,返回值。
- C++,当函数参数或者返回值是对象......(★firecat推荐★)
- JNI实现回调| JNI调用JAVA函数|参数和返回值的格式
- 3、定义一个结构体变量(包含年月日),计算该日在本年中为第几天?要求写一个days函数。参数是此结构体类型的变量,返回值是整数。
- const修饰函数参数,返回值,成员函数