首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c++类对象作为函数参数

c++类对象作为函数参数
EN

Stack Overflow用户
提问于 2018-10-09 11:50:21
回答 1查看 54关注 0票数 2

我正在做c++作业,我看到了一个奇怪的语法:

代码语言:javascript
复制
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关键字?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-09 11:55:42

它们是合法的,通常是不需要的。

只有当A是什么时,它们才是必需的。

例如:

代码语言:javascript
复制
#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;
};
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52720402

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档