【发布时间】:2018-05-28 04:54:02
【问题描述】:
我有一个程序,它有一个class A 类的实例和多个class B 类的实例,其中class B 的每个实例都有一个指向class A 的单个实例的指针。我想我可以在main() 中启动它们,然后将class A 的单个实例的地址传递给class B 的所有实例。我想知道这是否正确,我一直在研究继承,但根据我的理解(这通常是错误的),如果您继承另一个类,那么该类每次都会被启动,因此会创建多对多关系,而我想要一个太多。我附上了一些代码。任何建议将不胜感激。
// C/C++ standard library
#include <vector>
#include <iostream>
#include <cstdlib>
using namespace std;
class A {
public:
double get_value(void) {
return value;
}
private:
double value;
};
// Forward declare A if split over files
class B {
public:
void assign_pointer(A class_a_to_assign) {
class_a = &class_a_to_assign; // assign the pointer the address to point to
}
void update_my_value(void) {
value_b += class_a->get_value();
}
double get_value(void) {
return value_b;
}
private:
double value_b = 0.1;
A* class_a; // pointer to class A
};
int main() {
cout << "hello world" << endl;
// create 2 instances of B there could be thousands of these tho.
B b1;
B b2;
// create 1 instance of A
A a1;
// Now I want both instances of the B class to point to the one instance of A
b1.assign_pointer(a1);
b2.assign_pointer(a1);
// THen do stuff with B so that if any changes occur in A, then they can be automatically updated in class B through the pointer
b1.update_my_value();
b2.update_my_value();
cout << b1.get_value() << " and " << b2.get_value() << endl;
return 0;
}
【问题讨论】:
-
一个改进是在所有
B对象之前创建a1,以确保它比它们更长寿,因为它们依赖于它。 -
继承不是多对多的,它只是每个对象的一对一关系。 (此外,
A的前向声明不足以满足B的定义,并且您的示例读取自未初始化的A::value。)这里没有其他(显然)错误(即使可以做出重大改进)——这就是你的全部问题吗? -
另一个:确保
B只能从A*实例化,方法是在构造函数中进行:explicit B(A* a) : class_a(a) {}。