C++通过函数初始化类指针

标签 c++ class pointers

我有一个程序,它有一个类 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;
}

最佳答案

首先,您的代码中存在一个严重的问题:

void assign_pointer(A class_a_to_assign) {
    class_a = &class_a_to_assign; // assign the pointer the address to point to
}

这里,class_a_to_assign 是一个按值函数参数,它在生命周期方面与任何函数局部变量大致相同。换句话说,一旦控制离开方法的作用域,class_a 就会变成悬空指针(指向不再存在的本地对象的指针)。快速修复简单明了:

void assign_pointer(A &class_a_to_assign) {
    class_a = &class_a_to_assign; // assign the pointer the address to point to
}

区别仅在于一个字符 — 函数参数声明中的 & 符号将其从临时值转变为对更长期对象的引用。

接下来,如果您有一个 A 类 的对象,您是否考虑过将其设为单例?这样,B 的实例甚至不需要保留该指针,A 自己管理该实例。关于设计单例类已经有很多说法,粗略和天真的实现是这样的:

class A {
    A(); // note it's private
public:
    int getValue() const;
    static A &instance() {
        static A retVal;
        return A;
    };
};

class B {
public:
    void update_my_value(void) {
        value_b += A::instance().get_value();
    }
};

int main() {
    A::instance(); // to warmup the static instance before any users are created
    B b1; // no assign_pointer is needed as A is a Singleton
    B b2; // and every B always knows where to find it
}

关于C++通过函数初始化类指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50559328/

相关文章:

c++ - 基于 EBNF 语法的 C++ 下降递归解析器实现

ios - 错误: CoreData: warning: Unable to load class named '' for entity 'Receipt' . 但是类被删除了

java - 一个对象能知道它的方法是从哪个对象调用的吗?

c - C语言矩阵的二维数组和指针操作

c - 动态声明数组sizeof

pointers - Golang 中 []*Users 和 *[]Users 的区别?

c++ - boost 分词器但保留定界符

c++ - C++中的整数提升和整数转换有什么区别

c++ - 委派构造函数问题——安全吗?

c++ - Cuda C++ 设计 : reusable class with unknown compile-time size