是否可以在类定义之外定义运算符[]()(数组订阅)

  • 本文关键字:定义 数组 是否 运算符 c++
  • 更新时间 :
  • 英文 :


根据这篇文章:

数组订阅运算符是一个二进制运算符,必须作为类成员实现。

然后它提供了一个示例:

class X {
        value_type& operator[](index_type idx);
  const value_type& operator[](index_type idx) const;
  // ...
};

是否可以将此运算符定义为类定义之外的成员?

是的,您可以将其声明到类中,并将其定义为另一个翻译单元(或同一单元),如下所示

主.cpp

#include <iostream>
using namespace std;
class myClass {
    public:
    int operator[](int idx);
};
// Definition outside of the class
int myClass::operator[](int idx) {
    return 42;
}
int main() {
    myClass obj;
    cout << obj[55];
    return 0;
}

或类似以下内容

主.cpp

#include <iostream>
#include "header.h" <--
using namespace std;
int main() {
    myClass obj;
    cout << obj[55];
    return 0;
}

标题.h

#pragma once
class myClass {
    public:
    int operator[](int idx);
};

标头.cpp

#include "header.h"
// Definition outside of the class
int myClass::operator[](int idx) {
    return 42;
}

请记住 ODR - 一个定义规则:在任何翻译单元中,模板、类型、对象或函数不应超过一个定义。

最新更新