【问题标题】:C++ templates with friend function and operator overloading具有友元函数和运算符重载的 C++ 模板
【发布时间】:2016-04-14 09:56:48
【问题描述】:

我一直在将 c++ 模板添加到现有的运算符重载程序中,现在我遇到了这些错误。 我无法纠正这些错误,任何人都可以帮助我...... 这是代码... 我可以在简单的重载函数上进行模板化,但在朋友函数上有问题.. *****************注意:(更新) 整改后的代码... /演示操作员过载的程序/ #包括

template <class T>
class OP 
{
    T x, y, z;

    public:

    void IN()
    {
        std::cout << "Enter three No's : ";
        std::cin >> x >> y >> z;
    }

    void OUT()
    {
        std::cout << std::endl << x << " " << y << " " << z;
    }
    void operator~();
    void operator+(int);                    //Can accept both one or two argument

    template<class TA>
    friend void operator++(OP<T>);             //Accept one arguments (Unary Operator);

    template<class TB>
    friend void operator-(OP<T>, int);     //Accept two arguments     (Binary Operator)

    template<class TC>
    friend void operator!=(OP&, char t);
};

template<class T>
void OP<T>::operator~() //Unary Member Operator
{
    std::cout << std::endl << " ~ (tilde)";
}

template<class T>
void OP<T>::operator+(int y)    //Binary Member Operator
{
    std::cout << std::endl << "Argument sent is " << y;
}

template<class T>
void operator-(OP<T> &a, int t) //Binary Friend Operator
{
    a.x= a.x-t;
    a.y= a.y-t;
    a.z= a.z-t;
}

template<class T>
void operator!=(OP<T> &q, char t)   //Binary Friend Operator
{
    std::cout << std::endl << "Char " << t; 
}

template<class T>
void operator++(OP<T> x)    //Unary Friend Operator
{
    std::cout << std::endl << "Friend Unary Operator";
}

int main()
{
    OP <int> n, m;
    n.IN();
    m.IN();
    m+1;
    n!='t';
    int a = 1;
    char r='r';
    ~n;         //Member Function (Unary)
    n-a;        //Member Function (Unary)
    operator-(m, a);    //Friend Function (Binary)
    operator++(m);  //Friend Function (Unary)
    n.OUT();
    m.OUT();
    std::cin.get();
    return 0;
}

错误在所有三个友元函数上,错误是

现在我的好友功能无法访问私人会员...

【问题讨论】:

    标签: c++ templates c++11 operator-overloading


    【解决方案1】:

    如果您在 模板 类中声明友元函数,则必须在模板类定义中提供定义,或者在模板类之外重新声明。

    在模板类中将其声明为友元并不会在封闭范围内声明该函数。

    【讨论】:

    • 谢谢,使用第一个解决方案已经解决了问题,但你能告诉我如何在课堂外重新声明它..
    • 在声明带有friend语句的模板之前声明函数 - 与定义函数相同但没有主体。当然,在声明使用该类作为参数的函数之前,您需要前向声明模板类。
    猜你喜欢
    • 1970-01-01
    • 2011-04-28
    • 2016-09-09
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2011-03-19
    • 2021-05-18
    • 2011-06-07
    相关资源
    最近更新 更多