나는에서/이제 std::string
추상 형식의 필드를 선언 하시겠습니까? 포인터 또는 참조 선호?
struct Message
{
unsigned long id;
unsigned char command;
unsigned int value;
/* some more fields */
}
내가 다른 클래스``그은을함으로써 그 클래스에 의존하고 있습니다에 structure Message
를 분석 포맷에 대한
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;
}
같이 보입니다 추상 클래스가 그 유형의 회원. 내가 pProtocol
같은 포인터가 될 수 있기 때문에 내가 cProtocol
같은 클래스 형의 멤버를 선호한다 알고
: 물론이 멤버는 그래서 여기
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 }
의 하위 유형이 될 것으로 예상된다 나의 질문 있습니다
NULL
불행하게도이 메시지
로 컴파일되지 않습니다추상 클래스
Protocol
을 인스턴스화 할 수 없으므로 이해합니다.그래서 무엇을 선호합니까? 참조 멤버 또는 포인터 멤버?
3 가지 옵션의 차이점은 무엇입니까? 특히
cProtocol
사이rProtocol
내가 생성자에서
rProtocol
를 초기화하지 않는 경우 (.
대->
과 사실을 제외하고 포인터가NULL
될 수 있음)?이 컴파일됩니까? 무엇이 들어 있을까요? 이후 그것은 기본값으로 인스턴스화 될 수 없기 때문에!?
자세한 답변을 보내 주셔서 감사합니다. Java에서 왔고 객체 조각은 완전히 새로운 것이 었습니다! – ultimate