如果你有兩個類,a 類和 b 類,你能在 b 類中創建一個變數嗎? 主檔案
class A {
public:
A() {}
};
class B {
public:
B() {
test = A();
test.<variable name> = <variable value>;
}
};
上面的代碼只是一個例子。它可能會導致錯誤。
A類中不存在“變數名”。有沒有辦法在B類的建構式中為A類創建這個變數?
uj5u.com熱心網友回復:
不,C 不是 Javascript。型別是嚴格的,在定義型別之后,就無法修改它。
但是,您可以在函式中創建本地型別:
class B {
public:
B() {
struct A_extended : A {
int i;
};
auto test = A_extended();
test.i = 1;
}
};
uj5u.com熱心網友回復:
您需要提供適當的建構式、成員變數(可能還有 getter)。或者您需要向 a 添加一個 setter 并使用m_a.set_value(42).
#include <iostream>
class A
{
public:
// constructor for A with a value.
// made explicit to avoid implicit type conversions from int to A
explicit A(int value) :
m_value{ value }
{
};
int get_value() const noexcept
{
return m_value;
}
private:
int m_value;
};
class B
{
public:
B(int value) :
m_a{ value } // <-- this will pass value on to the constructor of A
{
};
const A& get_A() const noexcept // not good design, for educational purposes only
{
return m_a;
}
private:
A m_a;
};
int main()
{
B b{ 42 };
std::cout << b.get_A().get_value();
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/532982.html
標籤:C 班级哎呀
