zoukankan      html  css  js  c++  java
  • gcc的bug? c++模板类中友元函数的訪问权限问题

    原文地址:http://stackoverflow.com/q/23171337/3309790


    在c++中,模板类中能够直接定义一个友元函数。该函数拥有訪问该模板类非public成员的权限。

    比方:

    #include <iostream>
    using namespace std;
    
    template <typename T>
    class template_class {
        T v;
        friend void foo(template_class t) {
            t.v = 1;    // (1)能够訪问私有成员由于是友元函数
            cout << t.v << endl;
            template_class<int> t1;
            t1.v = 2;   // (2)能够訪问私有成员假设以[T=int]实例化
            cout << t1.v << endl;
            template_class<char> t2;
            t2.v = 'c'; // (3)不能够訪问私有成员假设以[T=int]实例化
            cout << t2.v << endl;
        }
    };
    
    int main() {
        template_class<int> t;  //(4)产生(实例化)void foo(template_class<int> t)
        foo(t);
        return 0;
    }

    (4)产生(实例化)出函数void foo(template_class<int>)的定义,而且使得它成为template_class<int>的友元。所以它能够訪问template_class<int>的私有成员,正如(1)和(2)所做的。

    可是(3)应该不能够,由于它并非template_class<char>的友元,仅仅有void foo(template_class<char>)是template_class<char>的友元。

    可是这段source能够在 gcc 4.8.1上编译通过,可是在clang 3.4编译失败。为什么?这仅仅是一个gcc的bug吗?c++标准对此有明白规定吗?

    /********************************************************************
    * 不落魄的书生的记事簿[blog.csdn.net/songyuanyao]
    ********************************************************************/
    
  • 相关阅读:
    struts1下载地址
    基础知识浮点数
    基础知识this[String]
    矩阵基础知识(二)
    矩阵基础知识(三)
    設計公司軟件開發需求分析流程
    動態調用js文件
    图片的淡入淡出的实现方法
    IIS7.5(经典/集成),IIS6,asp.net 4.0下配置Url映射(asp.net mvc)
    页面状态加载....
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5158643.html
Copyright © 2011-2022 走看看