C ++ - 使用指针作为数据字段复制构造函数

时间:2022-06-25 16:35:31

I have the following code :-

我有以下代码: -

#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;
}

It produces the output as :-

它产生的输出为: -

21
1
2

The behavior in case of c.get and d.get is easy to understand. Both c and d share the same pointer val and a and b share the same pointer val.

c.get和d.get的行为很容易理解。 c和d共享相同的指针val,a和b共享相同的指针val。

So c.get() should return 1 and d.get() should return 2. But I was expecting similar behavior in a.get() and b.get(). (maybe I have not understood cout properly)

所以c.get()应该返回1而d.get()应该返回2.但我期望在a.get()和b.get()中有类似的行为。 (也许我还没有正确理解cout)

I am unable to understand how a.get() is producing 2.

我无法理解a.get()是如何产生2的。

Can you explain why I am getting such an output. According to me the output should have been :-

你能解释一下为什么我会得到这样的输出。据我说,输出应该是: -

12
1
2

1 个解决方案

#1


6  

cout << a.get() << b.get() ;

gets executed as:

被执行为:

cout.operator<<(a.get()).operator<<(b.get());

In this expression, whether a.get() gets called first or b.get() gets called first is not specified by the language. It is platform dependent.

在此表达式中,语言不指定是先调用a.get()还是先调用b.get()。它取决于平台。

You can separate them into two statements to make sure they get executed in an expected order.

您可以将它们分成两个语句,以确保它们按预期顺序执行。

cout << a.get();
cout << b.get();

#1


6  

cout << a.get() << b.get() ;

gets executed as:

被执行为:

cout.operator<<(a.get()).operator<<(b.get());

In this expression, whether a.get() gets called first or b.get() gets called first is not specified by the language. It is platform dependent.

在此表达式中,语言不指定是先调用a.get()还是先调用b.get()。它取决于平台。

You can separate them into two statements to make sure they get executed in an expected order.

您可以将它们分成两个语句,以确保它们按预期顺序执行。

cout << a.get();
cout << b.get();