这应该是非常基本的.
布局:
class handler {
public:
handler(Connection *conn) { connection = conn; }
virtual void handle() = 0;
};
class http_status : public handler {
public:
http_status(Connection *conn) : handler(conn) { }
void handle();
};
class http_photoserver : public handler {
public:
http_photoserver(Connection *conn) : handler(conn) { }
void handle();
};
Run Code Online (Sandbox Code Playgroud)
码:
void pick_and_handle() {
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
} else {
http_status handler(connection);
}
handler.handle();
}
Run Code Online (Sandbox Code Playgroud)
这给出了一个错误:
../handler.cpp:51:10: error: expected unqualified-id before ‘.’ token
Run Code Online (Sandbox Code Playgroud)
我猜是因为编译器不知道什么处理程序是因为在if语句中创建了对象.我需要根据条件选择一个处理程序,我该怎么做?
显然这段代码有效:
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
handler.handle();
} else {
http_status handler(connection);
handler.handle();
}
Run Code Online (Sandbox Code Playgroud)
但是看起来不太性感!它真的是c ++的唯一方法吗?
当然,这不是唯一的方法.但您可能必须使用指针:
void pick_and_handle() {
unique_ptr<handler> http_handler;
if (connection->http_header.uri_str != "/")
http_handler.reset(new http_photoserver(connection));
else
http_handler.reset(new http_status(connection));
http_handler->handle();
}
Run Code Online (Sandbox Code Playgroud)
(相反的unique_ptr,你可以用boost::scoped_ptr,shared_ptr和auto_ptr也.但在这种情况下,unique_ptr并且boost::scoped_ptr是最合适的.)
使用指针,以获得多态行为:
auto_ptr<handler> theHandler = (connection->http_header.uri_str != "/") ?
new http_photoserver(connection) :
new http_status(connection);
theHandler->handle();
Run Code Online (Sandbox Code Playgroud)