首页 文章

在C中访问从一个类到另一个类的变量

提问于
浏览
-1

我试图从类 B 访问类 A 中声明的变量,而不使用 static 变量 . 我在头文件和源文件中分隔了类 .

我看到不同的人使用pass by reference(我假设在类定义中声明了“const&a”)但它对我不起作用 .

更新:当我尝试将A对象作为const-reference参数传递给B :: print时,我收到了一个错误 . 在我的例子中,我试图从 class B 中声明的函数 void print 访问 string a . 现在的问题是我在 B.cpp 中收到错误 .

main.cpp中

#include <iostream>
#include <string>
#include "A.h"
#include "B.h"

using namespace std;

int main()
{
    A first;
    B second;
    second.print(cout, first);
return 0;
}

#include <string>

using namespace std;


class A
{
    string a = "abc";
public:
    A();
    void print(ostream& o) const;
    ~A();
};

A.cpp

#include <iostream>
#include <string>
#include "A.h"
#include "B.h"

using namespace std;

A::A()
{
}

A::~A()
{
}

void A::print(ostream& o) const
{
    o << a;
}

ostream& operator<<(ostream& o, A const& a)
{
    a.print(o);
    return o;
}

B.h

#include <iostream>
#include <string>
#include "A.h"

using namespace std;

class B
{
public:
    B();
    void print(ostream&, A const&) const;
    ~B();
};

B.cpp

#include "B.h"
#include "A.h"
#include <iostream>
#include <string>

using namespace std;

B::B()
{
}
B::~B()
{
}
void B::print(ostream& o, A const& a) const
{
    o << a << endl;
    //^^ error no operator "<<" mathes these operands
}

2 回答

  • 1

    我'd do it is to pass in the A object to the B::print as a const-reference parameter. I'd的方式也传入ostream作为参考参数 . 而我'd take advantage of C++'的流输出操作符( << ) .

    像这样:

    #include <iostream>
    #include <string>
    
    using std::cout;
    using std::endl;
    using std::ostream;
    using std::string;
    
    class A
    {
        std::string s = "abc";
    public:
        void print(ostream& o) const;
    };
    
    void A::print(ostream& o) const
    {
        o << s;
    }
    
    ostream& operator<<(ostream& o, A const& a)
    {
        a.print(o);
        return o;
    }
    
    class B
    {
    public:
        void print(ostream&, A const&) const;
    };
    
    void B::print(ostream& o, A const& a) const
    {
        o << a << endl;
    }
    
    int main()
    {
        A first;
        B second;
        second.print(cout, first);
    }
    

    更新:鉴于上述评论,我不确定问题是“如何将代码拆分为单独的.h和.cpp文件?”或者它是否“如何从A访问成员变量,而不在A中使用静态变量?”

    更新:我将A的成员变量从 a 更改为 s ,以消除其他 a 标识符的歧义 .

  • 0

    由于 a 不是静态成员,因此在没有A类实例的情况下无法访问它 . 但是,您可以在函数中传递一个:

    class B {
        void print(const A &o) {
            cout << o.a << endl;
        }
    };
    

    此外,如果 a 成员是私有的,您可以将 class B 声明为朋友,这意味着它可以访问 class A 的私有成员和受保护成员 .

    class A {
        friend class B;
    private:
        std::string a = "abc";
    };
    

相关问题