欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-15 12:23:46
...
       什么时候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无权调用的成员函数,此时编译器就无能为力了。
相关标签: Effective C