c++类没有返回私有变量的正确值

C++ Class isn't returning the correct value of my private variable

本文关键字:变量 返回 c++      更新时间:2023-10-16

我试图让这个程序接受用户输入并将其放入公共函数并将其分配给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获取。object1object2是不同的对象。由于没有设置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为静态时才有效。