Effective C++学习笔记(四)

设计与声明

1.设计class犹如设计type

设计class前需要注意的问题:

  • 新type的对象应该如何创建和销毁--构造函数和析构函数
  • 对象的初始化和对象的赋值--构造函数和赋值操作符
  • 新type对象的 pass by value
  • 新type对象的“合法值”
  • 继承图系
  • 类型转换
  • pubilc、protected、private成员函数
  •  是否需要一个新type


2.宁以 pass-by-reference-to-const 替换 pass-vby-value

#include <iostream>

using namespace std;

class Person
{
public:
    Person()   .

    {
        cout<<"Person()"<<endl;
    }
    Person(const Person& p)
    {
        cout<<"Person(const Person& p)"<<endl;
    }
    virtual ~Person()
    {
        cout<<"~Person()"<<endl;
    }

private:
    string name;
    string address;
};


class Student:public Person
{
public:
    Student()
    {
        cout<<"Student()"<<endl;
    }
    Student(const Student& p)
    {
        cout<<"Student(const Student& p)"<<endl;
    }
    virtual ~Student()
    {
        cout<<"~Student()"<<endl;
    }


private:
    string schoolName;
    string schoolAddress;
};

bool validateStudent(Student s)
{
    return true;
}

int main()
{

    Student stu;
    bool s = validateStudent(stu);
    return 0;
}


上述主函数只有一个函数调用,来看一下运行结果:
       Effective C++学习笔记(四) - haidongli1991 - 爱学习的蓝调
 
发生了两次Person无参构造函数,一次Student无参构造函数,一次Student复制构造函数,四次析构函数(其实还有两次String构造函数和两次String析构函数)。如此看来,这样的代码效率并不是很高。
     修改validateStudent函数的参数调用:

bool validateStudent( const Student& s)
{
    return true;
}

Effective C++学习笔记(四) - haidongli1991 - 爱学习的蓝调
 
 
代码运行效率明显提高了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值