3

c++的良好习惯_爱写代码的小白程序员的技术博客_51CTO博客

 1 year ago
source link: https://blog.51cto.com/u_15059356/5638219
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

c++的良好习惯

精选 原创

爱写代码的小白程序员 2022-08-31 18:08:56 博主文章分类:C++ ©著作权

文章标签 初始化 赋值 构造函数 文章分类 嵌入式Linux 嵌入式 阅读数357

对象的初始化

1.使用对象前需要确保对象已经初始化

初始化和赋值

class PhoneNumber
{

};

class ABEntry
{
public:
ABEntry(std::string name, std::string address, std::list<PhoneNumber>& phone, int num);
private:
std::string mName;
std::string mAddress;

std::list<PhoneNumber> mPhones;
int mNumTimeConsulted;

};

// 赋值
ABEntry::ABEntry(std::string name, std::string address, std::list<PhoneNumber>& phone, int num)
{
mName = name;
mAddress = address;
mPhones = phone;
mNumTimeConsulted = num;
}

以上操作都是进行赋值操作,而不是初始化,这样能够带来你想要的成员变量的值,但是C++有更好的办法

初始化发生的阶段比较早,一般是在进入构造函数本地之前,所以更好的做法就是使用初始化模板

ABEntry::ABEntry(std::string name, std::string address, std::list<PhoneNumber>& phone, int num)
: mName(name),mAddress(address),mPhones(phone),mNumTimeConsulted(num)
{

}

这种做法的结果和上面的赋值操作是相同,但是相率更高,赋值操作需要调用进入构造函数本体里面进行操作,刚好初始化模板就避免了这个问题

2.构造析构和赋值

每一个所写的类都有一个或者多个默认构造函数,析构函数,copy assignment操作符

为了避免编译器为我们自动生成一些不是期待的相关函数,应该直接定义相关函数,拒绝编译器自动生成相关的函数

不要在构造函数和析构函数调用virtual相关的函数

class Transaction
{
public:
Transaction();
virtual void logTransaction() const = 0;
};


class BuyTransaction : public Transaction
{
public:
virtual void logTransaction() const;
};

class SellTransaction : public Transaction
{
public:
virtual void logTransaction() const;
};

Transaction::Transaction()
{
logTransaction();
}

BuyTransaction b; // 会发生什么?
c++的良好习惯_赋值
c++的良好习惯_构造函数_02
  • 1
  • 收藏
  • 评论
  • 分享
  • 举报

上一篇:c++ 之 const


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK