在 if 语句中创建对象时的范围问题 if C++ [英] Scope issue while creating objects inside if statement if C++

查看:53
本文介绍了在 if 语句中创建对象时的范围问题 if C++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是非常基本的.

布局:

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 语句中创建了对象.我需要根据条件选择处理程序,我该怎么做?

I'm guessing because compiler doesn't know what handler is cause object is created inside an if statement. I need to pick a handler based on a condition, how do I do that?

显然这段代码有效:

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

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

But doesn't look very sexy! Is it really the only way in c++?

推荐答案

当然这不是唯一的方法.但是你可能不得不使用指针:

Of course it's not the only way. But you may have to use pointers:

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

(您也可以使用 boost::scoped_ptrshared_ptrauto_ptr 代替 unique_ptr.但在这种情况下,unique_ptrboost::scoped_ptr 是最合适的.)

(Instead of unique_ptr, you can use boost::scoped_ptr, shared_ptr, and auto_ptr also. But in this case, unique_ptr and boost::scoped_ptr are most appropriate.)

这篇关于在 if 语句中创建对象时的范围问题 if C++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆