65,206
社区成员
发帖
与我相关
我的任务
分享
我想在两个类中互相调用,重载*操作符。怎么不行呢?
#ifndef A_H_
#define A_H_
#include "B.h"
class A
{
public:
int i;
A operator * (B b)
{
A a;
a.i=i*b.j;
return a;
}
};
#endif
#ifndef B_H_
#define B_H_
#include "A.h"
class B
{
public:
int j;
B operator * (A a)
{
B b;
b.j=j*a.i;
return b;
}
};
#endif
//主程序
#include<iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A a;
a.i=4;
B b;
b.j=5;
A c=a*b;
cout<<c.i<<endl;
return 0;
}
//A.h
#ifndef A_H_
#define A_H_
#include "B.h"
class B;
class A
{
public:
int i;
A operator * (B b);
};
#endif
//aa.app
#include "A.h"
A A::operator *(B b)
{
A a;
a.i=i*b.j;
return a;
}
//B.h
#ifndef B_H_
#define B_H_
#include "A.h"
class A;
class B
{
public:
int j;
B operator * (A a);
};
#endif
//bb.app
#include "B.h"
B B::operator *(A a)
{
B b;
b.j=j*a.i;
return b;
}
//主程序
#include<iostream>
#include "A.h"
#include "B.h"
using namespace std;
int main()
{
A a;
a.i=4;
B b;
b.j=5;
A c=a*b;
cout<<c.i<<endl;
B d=b*a;
cout<<d.j<<endl;
return 0;
}
这样可以,谁能帮忙解释一下?
class B;
class A
{
public:
int i;
A operator * (B b);
};
class B
{
public:
int j;
B operator * (A a)
{
B b;
b.j=j*a.i;
return b;
}
};
A A::operator*(B b)
{
A a;
a.i=i*b.j;
return a;
}
放到一个cpp文件还行。#include<iostream>
using namespace std;
class A
{
public:
A(int m=0): i(m) {}
int i;
int get() const { return i; }
};
class B
{
public:
B(int n=0): j(n) {}
int j;
int get() const { return j; }
};
template<class T1, class T2>
T1 operator*(const T1& lhs, const T2& rhs)
{
return (lhs.get() * rhs.get());
}
int main()
{
A a;
a.i=4;
B b;
b.j=5;
A c=a*b;
cout<<c.i<<endl;
system("pause");
return 0;
}