我正在做c++作业,我看到了一个奇怪的语法:
class A{
private:
string name;
public:
A(string n) :name(n){}
friend bool operator < (const class A& a1, const class A &a2);
}函数operator <的声明中有operator <关键字。我以前从未见过。这是一个很好的实践,还是我们可以直接删除class关键字?
发布于 2018-10-09 11:55:42
它们是合法的,通常是不需要的。
只有当A是什么时,它们才是必需的。
例如:
#include <string>
extern void A();
class A
{
private:
std::string name;
public:
A(std::string n) :name(n){}
friend bool operator < (const class A& a1, const class A &a2);
};
// removing `class` here would result in a compiler error as it would be
// ambiguous as to whether you meant the function A or the class A
bool operator < (const class A& a1, const class A &a2)
{
return a1.name < a2.name;
};https://stackoverflow.com/questions/52720402
复制相似问题