0

<<在我的代码中作为友元函数重载了。即使在级联时使用大括号后仍然存在错误

error: no match for ‘operator<<’ in ‘std::operator<< [with _Traits = 
std::char_traits<char>]((* & std::cout), ((const char*)"complex conjugate is ")) 
<< c.myComplex::operator~()’

我有一堂课myComplex

class myComplex
{
    private:
    float real;
    float imaginary;    

    public:
    myComplex();
    myComplex(float a,float b);
    friend std::ostream& operator<<(std::ostream& iso,myComplex& a);
    myComplex operator~() const;
};

的重载<<~构造函数如下,

std::ostream& operator<<(std::ostream& oso,myComplex& a)
{
    oso<<a.real<<" + "<<a.imaginary<<"i"<<std::endl;
return oso;
}

myComplex myComplex::operator~() const
{
    return myComplex(this->real,-1*this->imaginary);
}

myComplex::myComplex(float a,float b)
{
    real = a;
    imaginary = b;
}

我主要使用它如下,

Line 1:    std::cout << "c is " << c << "\n";
Line 2:    std::cout << "a is " << a << "\n";

Line 3: ((std::cout <<"complex conjugate is ")<<(~c))<<"\n";

Line 3:    std::cout <<"complex conjugate is "<<~c<<"\n";

第 1 行和第 2 行工作正常,但第 3 行给出了错误。如果它可以级联第 1 行和第 2 行并且因为~c也返回一个ostream为什么它会给出错误?

4

4 回答 4

3

临时对象(在这种情况下由 返回operator~())不能绑定到非const引用。将参数更改operator<<()const参考:

friend std::ostream& operator<<(std::ostream& iso,myComplex const& a);
于 2013-05-03T11:07:31.477 回答
2

使用const myComplex &代替myComplex &

friend std::ostream& operator<<(std::ostream& iso, const myComplex& a);
                                                   ^^^^^

当然,还要改变实施。

于 2013-05-03T11:07:25.297 回答
2

因为您operator~()按价值返回,所以您将一个临时对象输入您的ostream& operator<<此处:

std::cout <<"complex conjugate is "<< ~c <<"\n";
//                                    ^^ HERE! Temporary myComplex value.

运算符通过非常量引用获取其第二个参数myComplex&。非常量引用不能绑定到临时。将其更改为

std::ostream& operator<<(std::ostream& oso, const myComplex& a);
于 2013-05-03T11:08:22.153 回答
1

operator <<通过非 const 引用获取第二个参数,这意味着它不能绑定到临时(例如由 返回的那个~)。更改operator <<为接受const myComplex&作为第二个参数。

如果流输出运算符无论如何都修改了它的参数,那肯定会很奇怪。

顺便说一句,你知道 C++ 有一个内置类std::complex吗?

于 2013-05-03T11:09:04.540 回答