簡體   English   中英

在C ++中將變量從一個類訪問到另一個

[英]Accessing variables from one class to another in C++

我試圖從類B訪問類A聲明的變量,而不使用static變量。 我將類分為頭文件和源文件。

我見過不同的人使用按引用傳遞(我假設在類定義中聲明了“ const&a”),但它對我不起作用。

更新:當我嘗試將A對象作為const引用參數傳遞給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();
};

丙型肝炎

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

h

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

using namespace std;

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

丙型肝炎

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

我要做的方法是將A對象作為const-reference參數傳遞給B :: print。 我還要將ostream作為參考參數傳遞。 而且我會利用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文件?” 或者是“如何從B訪問A成員變量,而不在A中使用靜態變量?”

更新:我改變了A的成員變量從as的歧義與其他a標識符。

由於a不是靜態成員,因此沒有類A的實例就無法訪問它。但是,您可以在函數中傳遞一個:

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

此外,如果a成員是私有的,你可以聲明class B為好友,這意味着它可以訪問private和protected成員class A

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM