gpt4 book ai didi

c++ - 如果 C++ 在 if 语句中创建对象时出现范围问题

转载 作者:太空狗 更新时间:2023-10-29 23:24:17 25 4
gpt4 key购买 nike

这应该是非常基础的。

布局:

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();
};

代码:

void pick_and_handle() {
if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
} else {
http_status handler(connection);
}
handler.handle();
}

这给出了一个错误:

../handler.cpp:51:10: error: expected unqualified-id before ‘.’ token

我猜是因为编译器不知道处理程序是什么,因为对象是在 if 语句中创建的。我需要根据条件选择处理程序,我该怎么做?

显然这段代码有效:

  if (connection->http_header.uri_str != "/") {
http_photoserver handler(connection);
handler.handle();
} else {
http_status handler(connection);
handler.handle();
}

但看起来不是很性感!它真的是 C++ 中的唯一方法吗?

最佳答案

使用指针以获得多态行为:

auto_ptr<handler> theHandler = (connection->http_header.uri_str != "/") ?
new http_photoserver(connection) :
new http_status(connection);
theHandler->handle();

关于c++ - 如果 C++ 在 if 语句中创建对象时出现范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6329707/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com