English 中文(简体)
如何使用另一类变量
原标题:How to use a variable from another class

I have a class Overview where i try to save a Customer. Now i want to use that Customer in another class. Now i m using Public Static value, but my teacher said it s not good to use static variables. Can you solve this

public class OverView {
  public static Customer CurrentCustomer;

  CurrentCustomer = new Customer("Tom",23);
}

public class removeCustomer{

  Customer removeCustomer = OverView.CurrentCustomer;
}
问题回答

Your teacher is right, do not interface with static variables directly, implement getter/setter methods

。 ——————

更糟的是,在你的例子中,你根本不需要触及客户问题。 “搬走”功能应当是客户类别中的一种成员方法。 我甚至不敢肯定,你需要目前的保管人静态,但我保持静态。

public class Customer {

    //Customer constructor, etc.

    * * * 

    public void remove() {
        //remove the customer, whatever that entails
    }

}

public class OverView {

    private static Customer currentCustomer;

    public static void someMethod() {
        currentCustomer = new Customer("Tom",23);

        * * *

        //all done with this customer
        currentCustomer.remove();

        //but notice that the currentCustomer object still exists
    }
}

You need an instance of Overview to access its non-static members. Try:

public class OverView {
  public Customer CurrentCustomer = new Customer("Tom",23);
}

Public class removeCustomer{

  OverView ov = new OverView();
  Customer removeCustomer = ov.CurrentCustomer;
}

也可以建议不宣布现任监管机构为公众,并实行公众获取/获取途径





相关问题
Static variables in instance methods

Let s say I have this program: class Foo { public: unsigned int bar () { static unsigned int counter = 0; return counter++; } }; int main () { Foo a; Foo b; } (Of ...

Static function-scoped pointers and memory leaks

I ve written a simple library file with a function for reading lines from a file of any size. The function is called by passing in a stack-allocated buffer and size, but if the line is too big, a ...

Initialising a static variable in Objective-C category

I was trying to create a static variable to store a dictionary of images. Unfortunately, the best way I could find to initialise it was to check in each function that used the variable. Since I am ...

static variable initialisation code never gets called

I ve got an application that s using a static library I made. One .cpp file in the library has a static variable declaration, whose ctor calls a function on a singleton that does something- e.g. adds ...

热门标签