0

我有这样的课:

class A {
    ...private functions, variables, etc...
public:
    ...some public functions and variables...

    A operator * (double);
    A operator / (double);
    A operator * (A);
    ...and lots of other operators
}

但是,我也希望能够做一些事情,2 * A而不是只被允许做A * 2,所以我需要在课堂之外使用这样的功能:

A operator * (double, A);
A operator / (double, A);
...etc...

为了保持一致性,我应该将所有这些运算符放在课堂之外,还是应该一半在里面,一半在外面?

4

3 回答 3

2

恕我直言,关注的不应该是风格的一致性,而是封装的一致性;一般来说,如果一个函数不需要访问私有成员,它不应该是类的一部分。这不是一个硬性的快速规则,请参阅此处的论据。

因此,如果您的运营商不需要私人访问,请将它们全部放在外面。否则,它们都必须像这样在里面:

class A {
    ...
public:
    ...
    A operator * (double);
    A operator / (double);
    friend A operator * (double, A);
    friend A operator / (double, A);
    ...
};
于 2010-06-14T07:08:44.290 回答
2

From your replies to comments in the question it seems that you have an implicit conversion from double to A in your class. something like:

class A
{
    // ...
public:
    A(double);

    // ...
};

In this case you can simply define a free function for each operator of the form:

A operator*( const A&, const A& );

and it will be used if either side is an A object and the other side is implicitly convertible to an A. For this reason it is often preferable to make symmetric binary operators free functions.

Frequently it can be easier to implement binary * in terms of the assignment version *=. In this case I would make the assignment version a member function and define * as something like:

A operator*( const A& l, const A& r )
{
    A result(l);
    result += r;
    return result;
}

Otherwise as operator* is plainly part of your class interface I would have no problem with making it a friend if required.

于 2010-06-14T21:21:04.147 回答
1

So what you are saying is that because you must put some operators (the ones that don't have A as the first param) outside the class, maybe you should put them all there so people know where to find them? I don't think so. I expect to find operators inside the class if at all possible. Certainly put the "outside" ones in the same file, that will help. And if the outside ones need access to private member variables, then adding the friend lines is a huge hint to look elsewhere in the file for those operators.

Would I go so far as to include the friend lines even if my implementation of the operators could actually be done with public getters and setters? I think I would. I think of those operators as really being part of the class. It's just that the language syntax requires them to be free functions. So generally I use friend and I write them as though they were member functions, not using getters and setters. It's a pleasant side effect that the resulting need for friend statements will cause them all to be listed in the definition of the class.

于 2010-06-14T10:39:14.757 回答