请问:请帮小弟我看看下面几个类的有关问题,多谢
请教:请各位大哥帮我看看下面几个类的问题,谢谢!
请教:
m.h
class M
{
public:
A aa;
B bb;
int m;
};
a.h
class A
{
public:
int f1(){};
void f2(){};
};
b.h
class B
{
public:
B()
int f1();
void f2();
};
b.cpp
int B::f1()
{
m = aa.f1();
}
请教:
我想把所有的公共变量都定义在 类 M 里
问题1:
我在 int B::f1() 里使用了
m = aa.f1();
我需要把 在 类 B 里这样定义吗?
class B
{
public:
A aa;
int f1();
void f2();
};
还是怎么定义啊?
如果是这样定义我在 B 类怎么构造 A 啊
问题2:
还是用别的什么方法?
谢谢
------解决方案--------------------
如果你的m表示的是类M里的成员的话,m是类M的,你在B里不能用,aa.f1()里的f1是类A里的,在B里也不能用,你不仅要在B里定义A aa,还要在B里定义M mm,通过mm.m=aa.f1()。活着都在B::f1()函数里面定义,至于在BL类内怎么构造A,你没有定义A的构造函数,编译器给A定义了默认的构造函数,不用你关心了。
------解决方案--------------------
把 A 头文件包含既可
------解决方案--------------------
//m.h
#ifndef _M_H
#define _M_H
#include "a.h "
#include "b.h "
class M
{
public:
A aa;
B bb;
int m;
};
#endif
//a.h
#ifndef _A_H
#define _A_H
class A
{
public:
int f1(){ return 0;};
void f2(){};
};
#endif
//b.h
#ifndef _B_H
#define _B_H
class M;
class A;
class B
{
public:
B();
B(const B&);
~B();
B& operator=(const B&);
int f1();
int get_m()const;
void f2();
private:
A *pa;
M *pm;
};
#endif
//b.ccp
#include "b.h "
#include "a.h "
#include "m.h "
B::B():pm(new M),pa(new A)
{
//...
}
B::B(const B& cb):pm(new M),pa(new A)
{
pm-> m=cb.get_m();
//...
}
B& operator=(const B& cb)
{
if(&cb=this)
return;
//...
}
B::~B()
{
delete pm;
delete pa;
}
int B::f1()
{
pm-> m = pa-> f1();
return pm-> m;
}
int B::get_m()const
{
return pm-> m;
}
请教:
m.h
class M
{
public:
A aa;
B bb;
int m;
};
a.h
class A
{
public:
int f1(){};
void f2(){};
};
b.h
class B
{
public:
B()
int f1();
void f2();
};
b.cpp
int B::f1()
{
m = aa.f1();
}
请教:
我想把所有的公共变量都定义在 类 M 里
问题1:
我在 int B::f1() 里使用了
m = aa.f1();
我需要把 在 类 B 里这样定义吗?
class B
{
public:
A aa;
int f1();
void f2();
};
还是怎么定义啊?
如果是这样定义我在 B 类怎么构造 A 啊
问题2:
还是用别的什么方法?
谢谢
------解决方案--------------------
如果你的m表示的是类M里的成员的话,m是类M的,你在B里不能用,aa.f1()里的f1是类A里的,在B里也不能用,你不仅要在B里定义A aa,还要在B里定义M mm,通过mm.m=aa.f1()。活着都在B::f1()函数里面定义,至于在BL类内怎么构造A,你没有定义A的构造函数,编译器给A定义了默认的构造函数,不用你关心了。
------解决方案--------------------
把 A 头文件包含既可
------解决方案--------------------
//m.h
#ifndef _M_H
#define _M_H
#include "a.h "
#include "b.h "
class M
{
public:
A aa;
B bb;
int m;
};
#endif
//a.h
#ifndef _A_H
#define _A_H
class A
{
public:
int f1(){ return 0;};
void f2(){};
};
#endif
//b.h
#ifndef _B_H
#define _B_H
class M;
class A;
class B
{
public:
B();
B(const B&);
~B();
B& operator=(const B&);
int f1();
int get_m()const;
void f2();
private:
A *pa;
M *pm;
};
#endif
//b.ccp
#include "b.h "
#include "a.h "
#include "m.h "
B::B():pm(new M),pa(new A)
{
//...
}
B::B(const B& cb):pm(new M),pa(new A)
{
pm-> m=cb.get_m();
//...
}
B& operator=(const B& cb)
{
if(&cb=this)
return;
//...
}
B::~B()
{
delete pm;
delete pa;
}
int B::f1()
{
pm-> m = pa-> f1();
return pm-> m;
}
int B::get_m()const
{
return pm-> m;
}