gpt4 book ai didi

c++ - 成员与非成员函数,返回拷贝或引用?

转载 作者:行者123 更新时间:2023-11-30 00:45:58 26 4
gpt4 key购买 nike

对于成员函数和非成员函数应该具有哪种返回类型,是否有任何“规则”?

我正在构建一个复杂类,我认为成员函数是返回类型引用,非成员函数是拷贝。这是正确的吗?

供引用的Complex.h:

#include <iostream>
#include <string>

#ifndef COMPLEX_H
#define COMPLEX_H


class Complex {

public:
double real;
double imaginary;


Complex();
Complex(const double real);
Complex(const double real, const double imaginary);
Complex(const Complex &rhs);

Complex& operator *= (const Complex&);
Complex& operator += (const Complex&);
Complex& operator /= (const Complex&);
Complex& operator -= (const Complex&);
Complex& operator = (const Complex&);

};

class Complex;

double abs(const Complex& c);

Complex operator * (const Complex& c1, const Complex& c2);
Complex operator / (const Complex& c1, const Complex& c2);
Complex operator + (const Complex& c1, const Complex& c2);
Complex operator - (const Complex& c1, const Complex& c2);

bool operator == (const Complex& c1, const Complex& c2);
bool operator != (const Complex& c1, const Complex& c2);

std::istream& operator >> (std::istream& in, Complex& c);
std::ostream& operator << (std::ostream& out, const Complex& c);

Complex operator ""_i(long double arg);
Complex operator ""_i(unsigned long long arg);

#endif

最佳答案

这并不是关于成员(member)与非成员(member)的关系。您在成员函数中返回了引用,因为它们实际上修改了 this 值。

考虑以下代码:

Complex c1, c2, c3;
// ...
(c3 *= c2) += c1;

此处 c3 *= c2 将被评估,然后 operator+= 将以 c1 作为参数调用结果。如果您为 c3 *= c2 返回拷贝而不是引用,则下一个应用的 operator+= 将修改此返回的拷贝而不是 c3,这不是人们所期望的。

请注意,您也可以将其他运算符声明为成员函数,只是为了表明引用与拷贝与成员与非成员无关:

class Complex {

// ...

Complex& operator *= (const Complex&);
Complex& operator += (const Complex&);
Complex& operator /= (const Complex&);
Complex& operator -= (const Complex&);
Complex& operator = (const Complex&);

Complex operator * (const Complex& c2);
Complex operator / (const Complex& c2);
Complex operator + (const Complex& c2);
Complex operator - (const Complex& c2);

};

关于c++ - 成员与非成员函数,返回拷贝或引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40739486/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com