c ++模板似乎中断访问说明符 [英] c++ template seems to break access specifiers

查看:110
本文介绍了c ++模板似乎中断访问说明符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码不会编译明显的原因,即Foo尝试访问Bar的私有成员。但是,如果你取消注释/注释标记的行,使Foo一个模板,它会编译和输出42.我在这里丢失了什么?为什么这个工作?

The following code doesn't compile for obvious reasons, namely that Foo is trying to access a private member of Bar. However if you uncomment/comment the lines marked, making Foo a template, it does compile and outputs 42. What am I missing here? Why does this work? Seems to me it shouldn't.

感谢您的帮助。

#include <iostream>

class Bar {
    private:
    static const int x = 42;
};

//template <int>   // uncomment me
struct Foo {
    static const int i = Bar::x;
};

int main(int argc, char* argv[]) {

    std::cout << Foo::i    << std::endl;   // comment me
    //std::cout << Foo<0>::i << std::endl;   // uncomment me
}


推荐答案

Comeau Online和Visual C ++ 2010会将代码拒绝为无效,因为 Bar :: x 无法访问。 g ++ 4.1.2错误地接受无效的代码(有人需要测试与更高版本,看看是否已被修复;这是我在这台笔记本电脑上唯一的版本)。

Both Comeau Online and Visual C++ 2010 reject the code as invalid because Bar::x is inaccessible. g++ 4.1.2 incorrectly accepts the invalid code (someone would need to test with a later version to see if it's been fixed; that's the only version I have on this laptop).

这篇关于c ++模板似乎中断访问说明符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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