简单,可复制

点点滴滴,尽在文中

  :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

C++标准中提缺省构造函数、拷贝构造函数、拷贝赋值操作符和析构函数是特殊成员函数。

1.构造函数不能有返回类型,也不能由virtual, const, static 和 volatile来修饰。但可以由inline来修饰,事实上隐式构造函数就是用inline来修饰的。inline表示编译时展开,通常速度块;virtual表示运行时绑定,通常意味着灵活。

2.类中存在虚函数或者有虚基类的情况下需要显式声明构造函数。拷贝构造函数也是如此。

3.构造函数是一种特殊函数,而拷贝构造函数是一种特殊的构造函数。类X的构造函数的第一个参数必须为X&,或者const X&;除了第一个参数外,构造函数要么不存在其他参数,如果存在其他参数,其他参数必须有默认值。一个类可以有多个拷贝构造函数。它的形式如下:

X::X(X& x)
X::X(const X& x)
X::X(X& x, int a = 0, int b = 1…)

 什么时候会调用拷贝构造函数?以下三种情况出现时,会调用一个类的拷贝构造函数:
    1) 用一个已经实例化了的该类对象,去实例化该类的另外一个对象;
    2) 用该类的对象传值的方式作为一个函数的参数;
    3) 一个函数返回值为该类的一个对象。

示例代码如下:

#include <iostream>
using namespace std;

class PairInteger
{
public:
int m_a;
int m_b;
public:
inline PairInteger()
{
m_a = 1;
m_b = 2;
}

inline PairInteger(int a, int b)
{
m_a = a;
m_b = b;
}

inline PairInteger(const PairInteger& other)
{
m_a = other.m_a;
m_b = other.m_b;
cout << "copy constructor is called." << endl;
}

inline PairInteger(PairInteger& other)
{
m_a = other.m_a;
m_b = other.m_b;
cout << "copy constructor is called." << endl;
}

void printInfo()
{
cout << "a = " << m_a << ", b = " << m_b << endl;
}
};

int passObjectByValue(PairInteger pairInteger)
{
return pairInteger.m_a + pairInteger.m_b;
}

PairInteger returnObject(int a, int b)
{
PairInteger ca(a, b);
return ca;
}

int main(void)
{
PairInteger a;
//PairInteger b(); // 不能用这种方式声明CA的对象b
PairInteger c(10, 10);
PairInteger d(c); // 情况1) 用一个已经实例化了的该类对象,去实例化该类的另外一个对象
int anInt = passObjectByValue(c); // 情况2) 用该类的对象传值的方式作为一个函数的参数
PairInteger e = returnObject(11, 11); // 情况3) 一个函数返回值为该类的一个对象(在dev c++下没有调用拷贝构造函数,有待考察)
return 0;
}



posted on 2011-12-14 13:38  ggjucheng  阅读(7121)  评论(0编辑  收藏  举报