我是C++的新手,我遇到了一个问题。我正在尝试让每个类成为共同的朋友,并从一个类访问另一个类中的不同成员。我不知道我所做的是什么,wrong.Here是我到目前为止所拥有的:
#ifndef HA_H_
#define HA_H_
#include"Ha2.h"
using namespace std;
class two;
class one{
public:
int tip;
int timp;
one(int t) :tip(t){}
friend class two;
};
#endif /* HA_H_ */第二个标题:
#ifndef HA2_H_
#define HA2_H_
#include"Ha.h"
#include<vector>
class one;
class two{
public:
vector<one> v;
vector<int> x;
inline void create_x(vector<one> v){
// vector<one>::iterator it=v.begin();
int i;
for(i=0;i<v.size();i++){
x.push_back(v.at(i).tip);
}
}
friend class one;
};
#endif /* HA2_H_ */主要的是:
#include<vector>
#include<iostream>
#include"Ha.h"
#include"Ha2.h"
int main()
{
one o(3);
two x;
x.v.push_back(o);
x.create_x(x.v);
cout<< x.x.back();
}我得到了几个错误,比如:第二个类没有名为'v‘的成员
有什么建议吗?谢谢。
发布于 2011-04-04 06:08:44
main.cpp包括"Ha.h",在using namespace std;之前还包括"Ha2.h"。然后,定义class two,它将v声明为vector<one>,而不在std namespace中限定vector。
不需要在"Ha.h“中包含"Ha2.h”,删除它,然后限定向量。
发布于 2011-04-04 07:39:48
当类定义有指针或引用时,使用
using指令的整个目的无效。friend的用途,所以这至少应该使程序编译。Ha.h标题:
#ifndef HA_H_
#define HA_H_
class two ; // No pointers or references of two in one.
// So, remove it and place when you actually have
// a method taking reference of two.
class one{
public:
int tip;
int timp;
one(int t) :tip(t){}
friend class two;
};
#endif /* HA_H_ */Ha.cpp
#include "Ha2.h" // Place this only when have a method accessing
// members of two. Else this is unnecessary.
#include "Ha.h"
using namespace std ;Ha2.h
#ifndef HA2_H_
#define HA2_H_
class one ; // No pointers or references of one in two.
// So, remove it and place when you actually have
// a method taking reference of one.
class two{
public:
vector<one> v;
vector<int> x;
inline void create_x(vector<one> v)
{
// vector<one>::iterator it=v.begin();
int i;
for(i=0;i<v.size();i++)
{
x.push_back(v.at(i).tip);
}
}
friend class one;
};
#endif /* HA2_H_ */Ha2.cpp
#include <vector>
#include "Ha.h" // Place this only when have a method accessing
// members of two. Else this is unnecessary.
#include "Ha2.h"
using namespace std ;
// .....main.cpp
#include <vector> // Definitely need this because in the current unit, Ha2.h is
// included which has a data type of vector<int>
#include <iostream>
#include"Ha.h"
#include"Ha2.h"
using namespace std ; // vector and the other standard definitions are specified
// in std namespace
int main()
{
one o(3);
two x;
x.v.push_back(o);
x.create_x(x.v);
cout<< x.x.back();
}通过以上修改,您应该可以消除错误。如果出现任何新错误,请在您的问题中发布确切的错误消息。
发布于 2011-04-04 07:00:00
消除循环依赖的另一种方法是创建一个单独的头文件,如decl.h或任何您想要的头文件,并在其中简单地放入以下行:
#ifndef DECL_H_
#define DECL_H_
class one;
class two;
#endif DECL_H_然后在Ha.h和Ha2.h中删除#include "Ha.h"和#include "Ha2.h"行,并用#include "decl.h"替换它们。还要删除Ha.h和Ha2.h中的class one;和class two;声明,但保留每个类的定义。
现在你将不会有依赖于Ha2.h的Ha.h,反之亦然。
希望这能帮上忙
杰森
https://stackoverflow.com/questions/5532813
复制相似问题