ill*_*cal 2 c++ pointers class-constructors
我有以下代码: -
#include <iostream>
using namespace std;
class A {
int *val;
public:
A() { val = new int; *val = 0; }
int get() { return ++(*val); }
};
int main() {
A a,b = a;
A c,d = c;
cout << a.get() << b.get() ;
cout << endl ;
cout << c.get() << endl ;//
cout << d.get() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它产生的输出为: -
21
1
2
Run Code Online (Sandbox Code Playgroud)
在c.get和d.get的情况下的行为很容易理解.c和d共享相同的指针val,a和b共享相同的指针val.
所以c.get()应该返回1而d.get()应该返回2.但我期望在a.get()和b.get()中有类似的行为.(也许我还没有正确理解cout)
我无法理解a.get()是如何产生2的.
你能解释一下为什么我会得到这样的输出.据我说,输出应该是: -
12
1
2
Run Code Online (Sandbox Code Playgroud)
cout << a.get() << b.get() ;
Run Code Online (Sandbox Code Playgroud)
被执行为:
cout.operator<<(a.get()).operator<<(b.get());
Run Code Online (Sandbox Code Playgroud)
在此表达式中,语言不指定是先a.get()调用还是b.get()先调用.它取决于平台.
您可以将它们分成两个语句,以确保它们按预期顺序执行.
cout << a.get();
cout << b.get();
Run Code Online (Sandbox Code Playgroud)