其中,ClassA有一个运算符,返回ClassB:
class ClassA
{
public:
ClassA();
ClassB &operator[](int index);
}
Run Code Online (Sandbox Code Playgroud)
如果我想从ClassA的构造函数中访问所述运算符,如下所示:
ClassA::ClassA()
{
// How do I access the [] operator?
}
Run Code Online (Sandbox Code Playgroud)
目前,作为一种解决方法,我只是使用[]运算符调用的名为GetAtIndex(int index)的方法,构造函数也是如此.
如果我可以像C#一样访问它,那将是很好的:
// Note: This is C#
class ClassA
{
ClassB this[int index]
{
get { /* ... */ }
set { /* ... */ }
}
void ClassA()
{
this[0] = new ClassB();
}
}
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用g ++
可能需要重载下标运算符的场景是什么?
断言功能与此有什么关系?我在大多数情况下看到使用assert的下标重载,需要对此进行解释.
在std::queue与默认情况下,双端队列来实现.std::deque有下标运算符,operator[]并且可能用数组实现.那么,为什么std::queue有operator[]?
我意识到你可以有一个列表作为底层容器.(std::queue<int, std::list<int>>.)但即使这会使下标操作符变慢,这真的是一个不包含它的理由吗?这是我能想到它不包括在内的唯一原因.
是否可以定义一个operator[]需要多个参数的重载?也就是说,我可以定义operator[]如下:
//In some class
double operator[](const int a, const int b){
return big_array[a+offset*b];}
Run Code Online (Sandbox Code Playgroud)
然后像这样使用它?
double b=some_obj[7,3];
Run Code Online (Sandbox Code Playgroud) int main(){
int array[] = [10,20,30,40,50] ;
printf("%d\n",-2[array -2]);
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
任何人都可以解释-2 [array-2]是如何工作的,为什么[]在这里使用?这是我的任务中的一个问题,它给输出"-10",但我不明白为什么?
int n;//input size of array
cin >> n;
vector <int> a(n);
vector <int> in;
for (int i = 0; i < n; i++)
cin >> a[i];//input array elements
if (n == 1) {
cout << "1" << "\n";
return 0;
}
for (int i = 1; i <= n ; i++)//to get longest incresing subsequence in the array
{
int flag = 0, j = i;
while (j < n && a[j] >= a[j - 1] ) {
j++;
flag …Run Code Online (Sandbox Code Playgroud) 美好的一天.
我有以下结构和类,
template <class T>
struct Node
{
T DataMember;
Node* Next;
};
template <class T>
class NCA
{
public:
NCA();
~NCA();
void push(T);
T pop();
void print();
void Clear();
private:
Node<T>* Head;
void* operator new(unsigned int);
};
Run Code Online (Sandbox Code Playgroud)
我想实例化一个大小的类
即.NCA [30]就像任何数组一样
假设我有一个X类,它有2个属性:i和j.
我希望有 :
x = X((1,2,3),(2,3,4)) #this would set i to (1,2,3) and j to (2,3,4)
Run Code Online (Sandbox Code Playgroud)
我现在希望下标以下列方式工作:
a, b = x[1,2] #a should now be 2 and b should now be 3
Run Code Online (Sandbox Code Playgroud)
目前我正在尝试这个:
def __getitem__(self, i, j):
return self.x[i] , self.y[j]
Run Code Online (Sandbox Code Playgroud)
然而,这一直给我一个错误,getitem正好接受3个参数,但给出了2个(当我尝试打印x [1,2]时)
我写了一段代码,但似乎没有用.每次执行程序时,都会收到此错误
运行时检查失败#2 - 变量'ary'周围的堆栈已损坏
无论如何这里是我的代码(这是一个小代码)
#include <iostream>
using namespace std;
class Arrayz{
private:
int arry[5];
public:
Arrayz(){}
void setInf(){
for(int i = 0; i < 5; ++i){
cout << "Enter age of your friends: ";
cin >> arry[5];
}
}
const int& operator [](const int pos){
return arry[pos];
}
};
int main(){
Arrayz ary;
ary.setInf();
cout << "Here are your friend's age: " << endl;
for (int i = 0; i < 5; ++i){
cout << ary[i] << endl;
} …Run Code Online (Sandbox Code Playgroud)