C++模板,继承,派生相关

最近在做模板相关的开发,学习一下模板,继承,派生等相关操作中的注意点,记录如下:

virtual fun() const = 0

  1. virtual 表示写在基类中的函数
  2. const 表示函数中的类成员变量不能修改(有无const是两种类型的函数)
  3. =0 表明是纯虚函数,必须创建一个子类覆盖此函数(有const关键字的)

摘自stackoverfollow:

// You can't change the state of the object
// You can call this function via const objects
// You can only call another const member functions on this object
virtual void funcFoo() const = 0;
// You can change the state of the object
// You can't call this function via const objects
virtual void funcFoo() = 0;

模板化的工程中,C++的h文件和cpp文件的问题

在模板化的工程中,类的声明和实现一般不做分离(一定要分离的话,有相应的方法)

使用A.h定义,A_inl.h实现,然后中A.h的最后#include A_inl.h的方法不是分开定义,它们最后会合在一起

friend class

声明之后,可以给friend类相关的使用当前类成员函数的权限

使用 friend class声明类不一定需要头文件,如我在某个工程的头文件中加

friend class Efan<type>;
Efan<type> & efan_;

并不会报错

create two classes which use each other as data

不能使两个类直接包含其他类型的对象,因为否则将需要该对象的无限内存空间

不过可以通过使两个类指向彼此的指针来做到这一点,为此,需要使用提前声明以便两个类彼此知道对方的存在:

#ifndef BAR_H
#define BAR_H

class foo; // Say foo exists without defining it.

class bar {
public:
  foo* getFoo();
protected:
  foo* f;
};
#endif 
#ifndef FOO_H
#define FOO_H

class bar; // Say bar exists without defining it.

class foo {
public:
  bar* getBar();
protected:
  bar* f;
};
#endif 

请注意两个h文件互不包含。相反他们只是通过声明知道另一个类的存在。然后,在这两个类的.cpp文件中,可以#include另一个h文件来获取有关该类的完整信息。如此可避免循环引用的困局

//模板化的一个工程中的应用
// A.h
template<typename type>
class A{
    friend class B;
protected:
    B & b_;
//something else    
}
// B.h
template<typename type>
class A;
template<typename type>
class B{
    std::vector<shared_ptr<A>> as;
// something else
}
#include "B_inl.h"

// B_inl.h
#include "A.h"
// something else
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值