gpt4 book ai didi

c++ - 无法从友元函数访问私有(private)变量?

转载 作者:行者123 更新时间:2023-11-28 06:46:04 24 4
gpt4 key购买 nike

出于某种原因,我似乎无法从友元函数访问私有(private)变量。这是有问题的功能:

IntArray operator+(const IntArray& in1){
int secArray[SIZE];
IntArray a;
for (int i = low(); i <= compare(high(), in1.high()); i++){
a.iArray[i] = iArray[i] + in1.iArray[i]; // Combine elements of array to new array
}
return a(iArray);
}
else{
cout << "Error, second array larger than first. Exiting"; // If second array size is larger than first
exit(0);
}
}

这是我的头文件:

#ifndef _INTARRAY_H
#define _INTARRAY_H
#include <iostream>
#include <string>

using namespace std;

const int SIZE = 100;

class IntArray{
private:
int iArray[SIZE];
int arrLower, arrUpper;
int size;
string name;

public:
IntArray();
IntArray(int range);
IntArray(int lower, int upper);
IntArray(const IntArray& input);
int high() const;
int low() const;
int compare(int in1, int in2) const;
int operator==(const IntArray& in);
int operator!=(const IntArray& in);
void setName(string input);
IntArray& operator=(const IntArray& in);
int& operator[] (int size) { return iArray[size]; }
IntArray& operator+=( const IntArray& );
friend IntArray operator+( const IntArray in1 );
friend ostream& operator<<(ostream& os, const IntArray& i);



};



#endif

其次,这是对每个成员求和后返回数组的正确方法吗?

最佳答案

您的好友声明缺少引用声明符:

friend IntArray operator+( const IntArray in1 );

所以它是一个不同的函数。它必须与功能完全匹配:

       IntArray operator+(const IntArray& in1)

(此外,您还在默默地按值传递数组(慢!))

关于c++ - 无法从友元函数访问私有(private)变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24966638/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com