某些场景下,为了兼容接口,子类必须要实现接口中方法。例如面的接口。
#include <iostream>
#include <vector>
class A {
public:
virtual std::vector<uint8_t>& Get() = 0;
};
假如子类B和C,C中并不需要这个Get()方法,而B类需要,并且设置一个引用类型的成员变量
m_buff.
class B : public A {
public:
B(std::vector<uint8_t>& buffer) : m_buff(buffer)
{
}
std::vector<uint8_t>& Get()
{
return m_buff;
}
private:
std::vector<uint8_t>& m_buff;
};
而类C中为了兼容这种行为,也要实现同样的方法Get.但在类C的应用场景中,并不真的需要std::vector<uint8_t>这样的容器。此时会陷入两难,
1 假如类C中也设置引用类型的成员,因为引用成员必须在类的构造函数初始化列表中初始化,
这意味着构造器中必须要多一个参数
C(std::vector<uint8_t>& buffer) : m_buff(buffer)
{
}
它不能这样写(左值引用不能绑定到右值)
B(std::vector<uint8_t>& buffer) : m_buff({0}) // 左值引用不能绑定到右值
{
}
最简单的解决方法如下,直接在类C中定义一个普通成员,然后在C::Get()中返回
std::vector<uint8_t>,代码如下:
#include <iostream>
#include <vector>
class A {
public:
virtual std::vector<uint8_t>& Get() = 0;
};
class B : public A {
public:
B(std::vector<uint8_t>& buffer) : m_buff(buffer)
{
}
std::vector<uint8_t>& Get()
{
return m_buff;
}
private:
std::vector<uint8_t>& m_buff;
};
class C : public A {
public:
std::vector<uint8_t>& Get() {
return m_buff;
}
private:
std::vector<uint8_t> m_buff;
};
int main()
{
C *c = new C();
c->Get();
return 0;
}