【问题标题】:C++ - Copy constructor with pointers as the data fieldC++ - 使用指针作为数据字段的复制构造函数
【发布时间】:2016-04-13 22:22:01
【问题描述】:

我有以下代码:-

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

它产生的输出为:-

21
1
2

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

【问题讨论】:

    标签: c++ pointers class-constructors


    【解决方案1】:
    cout << a.get() << b.get() ;
    

    被执行为:

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

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

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

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

    【讨论】:

    • 所以我可以使用括号使其与 c 和 d 的情况一致?
    • @illogical,我想不出如何使用括号来强制命令,但您当然可以将它们分成两个语句。
    • @illogical,Precedence 未指定未指定的评估顺序。由于operator&lt;&lt; 是左关联的,就好像您已经像(cout &lt;&lt; a.get()) &lt;&lt; b.get(); 一样编写了它使用 b 结果调用。
    猜你喜欢
    • 2016-04-13
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    相关资源
    最近更新 更多