假设我定义了一些类:
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)
他们基本上做同样的事情,对吗?一个在堆栈上而另一个在堆上,所以我将在以后删除它.两者之间有什么根本区别吗?为什么我更喜欢一个呢?
我习惯于做Java编程,在编程时你永远不必考虑指针.但是,目前我正在用C++编写程序.在创建具有其他类成员的类时,何时应该使用指针,何时不应该使用指针?例如,我什么时候想要这样做:
class Foo {
Bar b;
}
Run Code Online (Sandbox Code Playgroud)
与此相反:
class Foo {
Bar* b;
}
Run Code Online (Sandbox Code Playgroud) // 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)