嗨,我有这个例子。
class Test
{
public:
Test(){m_x = 0;};
~Test() {};
void setX(const int x) {m_x=x;}
int getX() const {return m_x;}
private:
int m_x;
};
void SetX(Test& test)
{
int x = 2;
test.setX(x);
}
int main()
{
Test X;
SetX(X);
std::cout << "XX: " << X.getX() << std::endl;
return 0;
}
像这样设置类成员变量是否有效,或者当int x = 2超出范围时是随机行为吗?感谢您的帮助
这绝对是有效的,尽管有一个方法来设置变量,然后再有一个函数调用该方法,这有点多余。