相关疑难解决方法(0)

为什么不在C++中使用指针?

假设我定义了一些类:

class Pixel {
    public:
      Pixel(){ x=0; y=0;};
      int x;
      int y;
}
Run Code Online (Sandbox Code Playgroud)

然后使用它编写一些代码.我为什么要这样做?

Pixel p;
p.x = 2;
p.y = 5;
Run Code Online (Sandbox Code Playgroud)

来自Java世界我总是写:

Pixel* p = new Pixel();
p->x = 2;
p->y = 5;
Run Code Online (Sandbox Code Playgroud)

他们基本上做同样的事情,对吗?一个在堆栈上而另一个在堆上,所以我将在以后删除它.两者之间有什么根本区别吗?为什么我更喜欢一个呢?

c++ heap stack pointers

75
推荐指数
11
解决办法
1万
查看次数

何时使用指针而何时不使用?

我习惯于做Java编程,在编程时你永远不必考虑指针.但是,目前我正在用C++编写程序.在创建具有其他类成员的类时,何时应该使用指针,何时不应该使用指针?例如,我什么时候想要这样做:

class Foo {
    Bar b;
}
Run Code Online (Sandbox Code Playgroud)

与此相反:

class Foo {
    Bar* b;
}
Run Code Online (Sandbox Code Playgroud)

c++ java pointers

27
推荐指数
2
解决办法
7482
查看次数

C++参考和Java参考

// C++示例

#include <iostream>
using namespace std;

int doHello (std::string&);
int main() {
    std::string str1 = "perry";
    cout << "String=" << str1 << endl;
    doHello(str1);
    cout << "String=" << str1 << endl; // prints pieterson
    return 0;
}

int doHello(std::string& str){
    str = "pieterson";
    cout << "String=" << str << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,正如预期的那样,当修改str引用时,字符串'str1'引用被修改

// Java示例

public class hello {

    public static void main(String args[]){
        String str1 = "perry";
        System.out.println("String=" + str1);
        doHello(str1);
        System.out.println("String=" + str1); // does not …
Run Code Online (Sandbox Code Playgroud)

c++ java

11
推荐指数
2
解决办法
6076
查看次数

标签 统计

c++ ×3

java ×2

pointers ×2

heap ×1

stack ×1