-1

我的代码看起来像这样:

主文件

#include <iostream>
#include "A.h"
#include "B.h"
using namespace std;

int main(){

int d,f;
A c();
d = c.GetStuff();

B *d = new C();
f = d->Get();

return 0;
}

#ifndef A_H
#define A_H
class A
{
int a;

public A();

int GetStuff() {return(a) ;}

};

#endif

A.cpp

#include "A.h"

A::A()
{
 a = 42;//just some value for sake of illustration
}

溴化氢

#ifndef B_H
#define B_H

Class B 
{
public:
virtual int Get(void) =0;

};

class C: public B {
public:
C();

int Get(void) {return(a);}
};
#endif

B.cpp

#include "B.h"

C::C() {
a // want to access this int a that occurs in A.cpp
}

我的问题是,在 B.cpp 中访问“a”的最佳方法是什么?我尝试使用“朋友”类,但没有得到结果。

有什么建议么?谢谢!

4

1 回答 1

0

两个不同的答案,取决于你的意思

如果每个 A 对象都意味着有它自己唯一的“a”变量(这是您定义它的方式),那么您需要将 an 传递A给 的构造函数C

C::C(const A &anA) {
int foo= anA.a; // 
}

并且,调用构造函数变为:

A myA;
B *myC = new C(myA);   // You picked confusing names for your classes and objects

但是,如果您希望所有 A 对象共享一个共同的值a,那么您应该声明aandgetStuff如下:staticA

class A
{
static int a;  
public:
static int GetStuff() {return a;};

...并像A::GetStuff()C构造函数中一样访问它。

于 2013-03-14T22:40:40.473 回答