-1

私のコードは次のようになります。

main.cpp

#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
}

Bh

#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" にアクセスする最善の方法は何ですか? クラス "friend" を使用してみましたが、結果が得られません。

助言がありますか?ありがとう!

4

1 に答える 1

0

あなたが何を意味するかに応じて、2つの異なる答え

各 A オブジェクトが独自の一意の 'a' 変数を持つことを意図している場合 (これは、定義した方法です) A、のコンストラクターにan を渡す必要があり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 オブジェクトが共通の値を共有することを意図している場合は、 andを次のようにa宣言する必要があります。agetStuffstaticA

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

...そしてコンストラクターA::GetStuff()のようにアクセスします。C

于 2013-03-14T22:40:40.473 に答える