当运算符<<<<<<<<<<<<超载了

时间:2013-12-02 08:07:38

标签: c++

#include<climits>

class Int
{
    int *i, p;

    public:

    Int(){
        i = new int;
    }

    Int operator=(int a){
        *i = a , p = 7;
        return *this;
    }

    friend std::ostream& operator<<(std::ostream& os, const Int& dt);
};

std::ostream& operator<<(std::ostream& os, const Int& int_obj){
         // os << int_obj.p << '\n'; // accessible
         os << int_obj.*i << '\n'; // ERROR i was not declared int his scope
        return os; 
}

int main(){
    Int i;
    i = 5;
    std::cout << i;
}

在函数'std :: ostream&amp; operator&lt;&lt;(std :: ostream&amp;,const Int&amp;)':

错误:'i'未在此范围内声明

为什么我不能从这个对象的引用中访问我的指针变量?

2 个答案:

答案 0 :(得分:2)

使用:

os << *int_obj.i << '\n';

int_obj.*i毫无意义,您要求使用*i的{​​{1}}成员

}

另外,建议:Precedence table,为什么您不需要int_obj进行解除引用

答案 1 :(得分:1)

您错误放置了取消引用运算符。你想要这个:

os << *int_obj.i << '\n';

即,取消引用int_obj.i

表达式int_obj.*i将运算符.*应用于int_obj,将指针指向成员i。由于没有声明这样的i,编译器会抱怨。