错误:"VD<Class1> Class2::d ata"在此上下文中是私有的

error: 'VD<Class1> Class2::data' is private within this context

本文关键字:上下文 Class2 lt VD Class1 gt 错误 ata      更新时间:2023-10-16

我的代码有一些问题。我在.h中声明了两个朋友函数,它们是:

#ifndef CLASS2_H
#define CLASS2_H
#include "class1.h"
#include <string>
#include <iostream>
using namespace std;
class Class2{
private:

VD<Class1> data;    //Vector of objects of Class1

VD<int> number;      //Vector of int
public:
Constructor();
friend istream & operator >> (istream & i, const Class1 & other);

friend ostream & operator << (ostream &o, const Class1 & other);

};
#endif

.cpp是:

istream &  operator >> (istream & i,Class2 & other){
string n;
Class1 ing;
getline(i,n);
while(!i.eof()){
i >> ing;
otro.data.Insert(ing,otro.data.size()-1);
}
return i;
}

ostream &  operator << (ostream &o, const Ingredientes & otro){
for(int i = 0; i < otro.datos.size(); i++){
o << other.data[i];
}
return o;

}

所以,我得到的错误是:错误:"VD Class2::data"在此上下文中是私有的。我声明了运算符>>y<lt;朋友,但编译器对我说我不能访问私人数据,我对此毫无意义。请帮忙吗?

您似乎是C++的新手,而且您似乎在做一些非常复杂的事情,而您还不了解基本知识。请找到一个教程左右。

几件事:

  • using namespace std;——尤其是在标头中——从来都不是一个好主意。这就像你要去度假,但要把家里的一切都带上。请参阅使用std::的标准命名空间函数
  • CCD_ 3不能在声明为CCD_
  • 使用CCD_ 5是对CCD_ 6最基本的功能之一:CCD_
  • while (!i.eof())不好,因为eof直到读取结束后才被设置
  • 没有定义CCD_ 10函数。我们有std::stringstream

为了展示如何实现其中的一些功能,我将编写一些示例代码。请不要只是复制它,而是试着理解它。

test.txt

1 2 3 4
5 6 7 8

main.cpp

#include <vector>
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
template <typename T>
using VD = std::vector<T>;
class Class1 {
private:
int d;
public:
friend std::istream& operator>> (std::istream& i, Class1& obj) {
i >> obj.d;
return i;
}
friend std::ostream& operator<< (std::ostream& o, const Class1& obj) {
o << obj.d;
return o;
}
};
class Class2 {
private:
VD<Class1> data{};    //Vector of objects of Class1
public:
void Clear() { data.clear(); }
friend std::istream& operator>> (std::istream& i, Class2& obj) {
std::string line;
std::getline(i, line);
std::istringstream iss(line);
Class1 ing;
while (iss >> ing) {
obj.data.push_back(ing);
}
return i;
}
friend std::ostream& operator<< (std::ostream& o, const Class2& obj) {
for (auto const& cl1 : obj.data) {
o << cl1 << " ";
}
return o;
}
};
int main() {
Class2 cl2;
std::ifstream ifs;
ifs.open("test.txt");
if (ifs.is_open()) {
ifs >> cl2;
}
std::cout << "first line: " << cl2 << 'n';
cl2.Clear();
if (ifs.is_open()) {
ifs >> cl2;
}
std::cout << "second line: " << cl2 << 'n';
ifs.close();
}