我来自Java背景,并开始使用C++中的对象.但是我遇到的一件事是人们经常使用指向对象的指针而不是对象本身,例如这个声明:
Object *myObject = new Object;
Run Code Online (Sandbox Code Playgroud)
而不是:
Object myObject;
Run Code Online (Sandbox Code Playgroud)
或者,不要使用函数,比如说testFunc():
myObject.testFunc();
Run Code Online (Sandbox Code Playgroud)
我们要写:
myObject->testFunc();
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚为什么我们这样做呢.我认为它与效率和速度有关,因为我们可以直接访问内存地址.我对吗?
请考虑以下示例.
String str = new String();
str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
Run Code Online (Sandbox Code Playgroud)
现在,在Java中,String对象是不可变的.那么为什么对象str可以赋值"帮助!".这与Java中字符串的不变性相矛盾吗?任何人都可以向我解释一下不变性的确切概念吗?
编辑:
好.我现在得到它,但只是一个后续问题.以下代码如何:
String str = "Mississippi";
System.out.println(str); // prints Mississippi
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
Run Code Online (Sandbox Code Playgroud)
这是否意味着再次创建了两个对象("Mississippi"和"M!ss!ss!pp!"),并且引用str指向replace()方法之后的另一个对象?
我有一个像下面的大开关:
public int procList(int prov, ArrayList<TXValue> txValueList, Context context)
{
switch(prov)
{
case Foo.PROV_ONE:
return proc_one(txValueList, context);
case Foo.PROV_NOE:
return proc_noe(txValueList, context);
case Foo.PROV_BAR:
return proc_bar(txValueList, context);
case Foo.PROV_CABAR:
return proc_cabar(txValueList, context);
case Foo.PROV_FAR:
return proc_far(txValueList, context);
case Foo.PROV_TAR:
return proc_tar(txValueList, context);
case Foo.PROV_LBI:
return 408;
default:
return -1;
}
}
Run Code Online (Sandbox Code Playgroud)
在c ++中,我可以std::map<Foo, some_function_ptr>按照以下方式使用和使用它:
map[prov](txValueList, context);
Run Code Online (Sandbox Code Playgroud)
Java中没有指向函数的指针.但是,它使用抽象类,就像它在答案中一样.那么,有没有一种最好的方法来消除switchjava中的大条款?
我使用了很多 C++,但我对 Java 的工作方式感到很困惑:如果我有一个类
public class MyClass{
private int[] myVariable;
...
public int[] getVar(){
return myVariable;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我想在其他地方使用我的变量:
public static void main(String[] args){
MyClass myObject = new MyClass();
...
int[] temp = myObject.getvariable();
// use of temp
...
}
Run Code Online (Sandbox Code Playgroud)
temp 是 myVariable 的副本还是引用?
你如何获得副本/参考?
我知道java中的所有内容都是按值传递的,但下面的代码不应该打印2而不是1。
我所做的只是传递Integer和改变它的价值。为什么打印 1 而不是 2 ?
public static Integer x;
public static void doChange(Integer x) {
x = 2;
}
public static void main(String arg[]) {
x = 1;
doChange(x);
System.out.println(x);
}
Run Code Online (Sandbox Code Playgroud)