简体   繁体   English

java中::运算符的等价物是什么?

[英]What is the equivalent of :: operator in java?

When accessing a function from another class in c++, we can write: classA::fct();在c++中访问另一个类的函数时,我们可以这样写: classA::fct();

Is there an equivalent operator in java? java中有等价的运算符吗? If not, how can we access a function from another class in java?如果没有,我们如何从java中的另一个类访问函数?

Well the :: -operator ( Scope Resolution Operator ) in C++ allows you to resolve ambiguous calls/references to identifiers.好吧,C++ 中的:: -operator ( Scope Resolution Operator ) 允许您解决对标识符的不明确调用/引用。 However, in java there are no independent functions as all functions are actually methods (members) of a class.但是,在 java 中没有独立的函数,因为所有函数实际上都是类的方法(成员)。 As such there are no need for this operator, have a look here for differences between Java and C++ classes.因此不需要此运算符,请查看此处以了解 Java 和 C++ 类之间的差异。

I am guessing you are attempting to access a member (possibly static) of a class, in which case you'd use the .我猜您正在尝试访问类的成员(可能是静态的),在这种情况下,您将使用. -operator as exemplified in Mwesigye's answer or as follows: -如Mwesigye 的回答中所示或如下所示:

public class AB {
    public static void main(String[] args) {
        B myB = new B();
        myB.printA();
    }
}

public class A {
    public static int getInt() {
        return 4;
    }
}

public class B {
    public void printA() {
        System.out.println(A.getInt()); // output: 4
    }
}

Here the .这里的. -operator is used to access printA() from the instantiated object myB (instantiated from class B). printA()用于从实例化对象myB (从类 B 实例化printA()访问printA() )。 It is also used to access the static method getInt() whose implementation is tied to class A rather than any object of A. More info can be found here .它还用于访问静态方法getInt()其实现绑定到类 A 而不是 A 的任何对象。更多信息可以在这里找到。

Take an example of a Class Student with methods what you call functions in c++ eg.举一个 Class Student 的例子,它有你在 C++ 中称之为函数的方法,例如。

    class Student{ 
    //a non static method
    public void getFees(){
    //your logic
    }  
    public static void deleteSubject(){
    // your logic
    }

} 
class Club{
  //create a new instance of student class
Student student = new Student();
public void printData(){ 
//access a non static method  
student.getFees(); 
//accessing a static method 
new Student().deleteSubject();
}

} 

Hope this will help.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM