返回对象时,我不能简单地在类名后使用 {}

When returning an object, I can't simply use {} after class name

本文关键字:对象 简单 不能 返回      更新时间:2023-10-16

以有关嵌套类的教育代码为例:

class enclose {
    struct nested { // private member
        void g() {}
    };  
public:
    static nested f() { return nested{}; } 
};   
int main() {
    //enclose::nested n1 = e.f(); // error: 'nested' is private
    enclose::f().g(); // OK: does not name 'nested'
    auto n2 = enclose::f(); // OK: does not name 'nested'
    n2.g(); }

将此代码复制并粘贴到Microsoft Visual Studio 2012时,我会在Line中出现错误

static nested f() { return nested{}; }

问题与函数返回嵌套的方式有关。这不是我第一次看到代码以这种方式返回值,但是我通常会忽略它,并以更长的方式进行。这是编译器问题吗?

return nested{};

采用新的C 11支撑启动化,并将对象进行价值化。如您在此处看到的那样,Visual Studio 2012(VC11)不支持Braced Initialization,因此您会遇到编译时间错误。

唯一的解决方案是使用

return nested();

而不是更新编译器。