我的类B不是前面声明了吗,怎么还报错?
#define _CRT_SECURE_NO_WARNINGS#include <iostream>
using namespace std;
//友元关系不能被继承,不具有传递性,是单向的,不具有交换性
class B;
class A
{
public:
A(int a)
{
this->a = a;
}
void printA(){
B objB(3000);
cout << objB.b << endl;
cout << "a = " << this->a << endl;
}
//声明一个友元类B
friend class B;
private:
int a;
};
class B
{
public:
B(int b)
{
this->b = b;
}
void printB(){
A objA(100);
cout << objA.a << endl;
cout << "b = " << this->b << endl;
}
//声明一个友元类B
friend class A;
private:
int b;
};
int main(void)
{
B objB(200);
objB.printB();
A objA(2000);
objA.printA();
return 0;
} 本帖最后由 jessylake 于 2017-12-19 11:24 编辑
看来声明的还不够彻底,要把B类完全拆开
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//友元关系不能被继承,不具有传递性,是单向的,不具有交换性
class B
{
public:
B(int b);
void printB();
//声明一个友元类A
friend class A;
private:
int b;
};
class A
{
public:
A(int a)
{
this->a = a;
}
void printA(){
B objB(3000);
cout << objB.b << endl;
cout << "a = " << this->a << endl;
}
//声明一个友元类B
friend class B;
private:
int a;
};
B::B(int b)
{
this->b = b;
}
void B::printB(){
A objA(100);
cout << objA.a << endl;
cout << "b = " << this->b << endl;
}
//class B
//{
//public:
// B(int b)
// {
// this->b = b;
// }
//
// void printB(){
// A objA(100);
// cout << objA.a << endl;
// cout << "b = " << this->b << endl;
// }
// //声明一个友元类A
// friend class A;
//private:
// int b;
//};
int main(void)
{
B objB(200);
objB.printB();
A objA(2000);
objA.printA();
return 0;
}
有道理,让我这小白又学习了
页:
[1]