Effective C++笔记之五:了解C++默默编写并调用哪些函数

       什么时候empty class(空类)不再是个empty class呢?当C++处理过它之后。是的,如果你自己没声明,编译器就会为它声明(编译器版本的)一个copy 构造函数、一个copy assignment操作符和一个析构函数。此外如果你没有声明任何构造函数,编译器也会为你声明一个default构造函数。所有这些函数都是public且inline。因此,如果你写下:
class Empty {};
       这就好像你写下这样的代码:
class Empty  
{  
public:  
  Empty(){.....}       //default构造函数  
  ~Empty(){.....}      //析构函数  
  Empty(const Empty & rhs) {.....}              //copy构造函数  
  Empty & operator=(const Empty & rhs) {.....}  //copy assignment操作符  
};  
       惟有当这些函数被需要(被调用),它们才会被编译器创建出来。下面代码造成上述每一个函数被编译器产出:
Empty e1;    //default构造函数
             //析构函数
Empty e2(el);//copy构造函数
e2 = e1;     //copy assignment操作符
需要注意的:
1.编译器产出的析构函数是个non-virtual,除非这个class 的base class自身声明有virtual析构函数(这种情况下这个函数的虚属性(virtualness)主要来自base class)。
2.如果手动声明了一个构造函数,编译器不再为它创建default构造函数.
3.默认赋值运算符不能生成的3种情况:数据成员是引用型、const型或者父类的赋值运算符声明为private。例如:
#include <iostream>
#include <string>

class Dog 
{
public:
	Dog(const std::string& name, const int age)
	{
		this->name = name;
		this->age = age;
	}
	~Dog(){ }
private:
	std::string& name;
	const int age;
};

void main()
{
	std::string name1("Big Yellow");
	std::string name2("Big Yellow");
	Dog bigYellow1(name1, 3); // 大黄1于去年归西了
	Dog bigYellow2(name2, 4);
	bigYellow1 = bigYellow2;  // 大黄2取代了大黄1的位置
	                          // error C2582: “operator =”函数在“Dog”中不可用
}
       导致error是因为C++并不允许"让reference改指向不同对象",且更改const成员是不合法的。                          
#include <iostream>
#include <string>

class Animal
{
public:
	~Animal(){};
private:
	Animal & operator=(const Animal & rhs); //copy assignment 操作符 
};

class Dog :public Animal 
{
public:
	Dog(const std::string& name, const int age)
	{
		this->name = name;
		this->age = age;
	}
	~Dog(){ }
private:
	std::string name;
	int age;
};

void main()
{
	std::string name1("Big Yellow");
	std::string name2("Big Yellow");
	Dog bigYellow1(name1, 3); // 大黄1于去年归西了
	Dog bigYellow2(name2, 4);
	bigYellow1 = bigYellow2;  // 大黄2取代了大黄1的位置
	                          // error C2248: “Animal::operator =”: 无法访问 private 成员(在“Animal”类中声明)
}                   
       导致error是因为如果某个base classes将copy assignnment操作符声明为private,编译器将拒绝为其derived classes生成一个copy assignment操作符。毕竟编译器为derived classes所生的copy assignment操作符想象中可以处理base class成分,但它们当然无法调用derived class无权调用的成员函数,此时编译器就无能为力了。
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草上爬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值