c++类没有返回私有变量的正确值
C++ Class isn't returning the correct value of my private variable
我试图让这个程序接受用户输入并将其放入公共函数并将其分配给privatvariable,然后我希望它将privatvariable的值返回给main()并将其输出到屏幕,但它所显示的是一个未定义的int(-858993460)的值。我这里有什么逻辑问题?
#include <iostream>
#include <string>
using namespace std;
class MyClass
{
private:
int privateVariable;
public:
int userVariable;
void setVariable(int userVariable)
{
privateVariable = userVariable;
}
int getVariable()
{
return privateVariable;
}
};
int main()
{
int userVariable;
cin >> userVariable;
MyClass object1;
MyClass object2;
object1.setVariable(userVariable);
object2.getVariable();
cout << object2.getVariable();
system("PAUSE");
return 0;
}
您正在设置object1
并从object2
获取。object1
和object2
是不同的对象。由于没有设置object2
中的变量,您将获得一个垃圾值。
And I see no use public userVariable
in MyClass
.
您没有设置变量。在object1
上调用setVariable
,在object2
上调用getVariable
,因此object1
的成员保持未初始化状态。
object1.setVariable(5); // object1.privateVariable = 5
// object2.privateVariable -> still uninitialized
object2.getVariable(); // returns uninitialized variable
要让这个工作,取决于你想要什么:
class MyClass
{
private:
static int privateVariable;
//......
}
这样,privatvariable将是类作用域的成员,而不是实例作用域的成员。这意味着它对类的所有实例具有相同的值(即使没有创建实例)。这也意味着您可以将这两个函数设置为静态:
class MyClass
{
private:
static int privateVariable;
public:
static void setVariable(int userVariable)
{
privateVariable = userVariable;
}
static int getVariable()
{
return privateVariable;
}
};
,你可以调用没有实例的方法:
MyClass::setVariable(5); //MyClass.privateVariable = 5;
MyClass::getVariable(); //returns 5
object1.getVariable(); //returns also 5
另一个选择是,如果你不想要静态成员,为两个对象设置成员:
object1.setVariable(5); // object1.privateVariable = 5
// object2.privateVariable -> still uninitialized
object2.setVariable(5); //object2.privateVariable = 5
object2.getVariable(); // returns 5
或者,您可以定义一个构造函数并在那里设置变量:
class MyClass
{
private:
static int privateVariable;
//......
public:
MyClass()
{
privateVariable = 5;
}
}
这样,你创建的每个对象都将成员初始化为5。
object2没有初始化您在object1上设置的变量,您发布的代码仅在privatvariable为静态时才有效。
相关文章:
- 你能重载对象变量名本身返回的内容吗
- 如何在 c++ 中让布尔变量返回为 0 或 1 而不是真或假?
- 从私有成员变量的成员方法返回unique_ptr
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- C++ 根据给定的类型名从变量返回数据
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- C++ 在静态函数中使用非静态变量返回类实例
- 具有变量返回类型的函数
- 带有 QVariant 和模板的变量返回类型
- getenv() 在不同的程序中为同一环境变量返回不同的值
- C 多重继承,虚拟方法覆盖问题和协变量返回类型
- 变量返回类型
- C++函数向字符串变量返回int
- 从临时变量返回的引用是否有效
- 有没有一种方法可以将C++数据类型作为变量返回
- 类函数的模板变量返回类型
- C++函数,使用'auto'变量返回类型
- 如何将引用变量返回到函数中
- 变量返回类型上转换覆盖c++
- 数组变量返回意外值