如何将在一个类中声明的类的数据类型访问到另一个类(两者都在不同的翻译单元中)

How to access data type of a class declared in one class into another class (both in different translation unit)?

本文关键字:两者都 另一个 单元 翻译 访问 数据类型 一个 声明      更新时间:2023-10-16

我有5个文件。(1. A.hpp, A.cpp: 2。b.h hpp, b.p p: 3 main.cpp)

// A.hpp
#ifndef MY_CLASS_A
#define MY_CLASS_A
#include <iostream>
class B; // forward declaration so that I could do B * b;
struct s {
    int x;
    double y;
};
class A{
    s my_struct;
    int size;
    B * b;
public:
    A(int, double, int);
    void f1(s);
    void f2(); // this function calls B's f1 function
    s get_struct();
    int get_size();
    void print();
};
#endif

然后我将其实现为

// A.cpp
#include "A.hpp"
#include "B.hpp"
A::A(int x_, double y_, int size_):my_struct({x_, y_}), size(size_){}  
void A::f1(s s_){
    // do stuff   
    s_.x = 5;
    s_.y = 51.99;
}
void A::f2(){
    int val;   
    // Here I am calling B's f1 function
    val = b->f1(my_struct);
}
s A::get_struct(){
    return my_struct;
}
int A::get_size(){
    return size;
} 
void A::print(){
    std::cout << " ----- " << std::endl;
    std::cout << "x    = " << my_struct.x << std::endl;
    std::cout << "y    = " << my_struct.y << std::endl;
    std::cout << "size = " << size << std::endl; 
    std::cout << " ----- " << std::endl;
}

然后是B

//B.hpp
#ifndef MY_CLASS_B
#define MY_CASS_B
#include "A.hpp" // I placed here A.hpp because I am 
                 // trying to use A's struct type 
class A;
class B{
public:
    int f1(s); // A's struct use here to get struct by value
};
#endif

及其作为

的实现
// B.cpp
#include "B.hpp"
 //  used A's struct here again
int B::f1(s my_struct){ 
    std::cout << "*****" << std::endl;
    std::cout << my_struct.x << std::endl;
    std::cout << my_struct.y << std::endl;
    std::cout << "*****" << std::endl;
}

finally main as

// main.cpp
// As per comment I should place #include "A.hpp" here 
#include "A.cpp"
int main(){
    A a(4,9.9, 5);
    a.print();
    return 0;
}

我的主要问题是如何将A类中声明的结构访问到B类中?我尝试过使用forward declaration,但是失败了。

打开c++课本,翻到指针和引用那一章,再读一遍。

"在类A中声明的结构体"是my_struct,它是private类成员。

要在其他地方访问它,需要通过引用传递它。

int B::f1(const s &my_struct){ 
    std::cout << "*****" << std::endl;
    std::cout << my_struct.x << std::endl;
    std::cout << my_struct.y << std::endl;
    std::cout << "*****" << std::endl;
}

现在,当你从A调用这个:

val = b->f1(my_struct);

现在将传递对my_struct成员的引用,而不是复制它。

注意,这个参数被声明为对sconst实例的引用,因为f1()不需要修改它。如果存在,只需将其作为非const引用传递:

int B::f1(s &my_struct){ 

现在,f1()将能够修改my_struct,并最终修改传递给A的类的私有实例。

注:这与不同的翻译单位无关。无论整个事情是在一个翻译单元中,还是被分成六个翻译单元,类和引用的工作方式都是一样的。

相关文章: