我有一个抽象类,看起来像声明抽象类型的字段?喜欢指针还是参考?
class Protocol
{
public:
// format the string to json or xml depending on impl
virtual std::string& format(Message& msg) = 0;
// parse the message from json or xml depending on impl
virtual Message& parse(std::string& str) = 0;
}
格式化解析structure Message
从/到std::string
struct Message
{
unsigned long id;
unsigned char command;
unsigned int value;
/* some more fields */
}
现在我有另一个类``是由具有依赖于类该类型的成员。当然,这件有望成为Calculator
// client.h
class Client
{
public:
Client(Protocol& protocol);
/* some methods, e.g. */
void request(unsigned int amout);
private:
/* this is what the question below refers to */
Protocol* pProtocol; // will compile
Protocol cProtocol; // won't compile (see below)
Protocol& rProtocol; // what does this mean?
}
// client.cpp
Client::Client(Protocol& protocol) :
// depending on the member
pProtocol(&protocol) // or
cProtocol(protocol) // or
rProtocol(protocol)
{
}
void Client::request(unsigned int amount)
{
Message msg;
msg.id = 1234;
msg.command = 100;
msg.value = amount;
std::string str =
// depending on the member
pProtocol->format(msg); // or
cProtocol.format(msg); // or
rProtocol.format(msg);
// some more code to send the string to the server
}
所以这里亚型的是我的问题:
我知道我应该更喜欢类类型的成员像
cProtocol
因为像pProtocol
指针可能NULL
不幸的是这不会对消息
编译我明白了,因为抽象类
Protocol
不能实例化。因此我应该选择什么?一个引用成员或一个指针成员?
3个选项之间有什么区别?特别是与
rProtocol
之间cProtocol
(除.
与->
和事实指针可能NULL
)如果我不初始化在构造函数
rProtocol
?这会编译吗?它包含什么?由于它不能用默认值实例化!?
感谢您的详细解答。我来自Java,对象切片对我来说是全新的! – ultimate 2014-10-08 14:13:28