实现复制的简单C ++程序中的输出错误

时间:2019-03-18 16:31:36

标签: c++

    #include<iostream>
#include<vector>
using namespace std;
class test{
    int a,b;
    public:
    test():a{0},b{0}{}
    test(int,int);
    void copy(test);
    void print();
};
test::test(int a,int b){
    a=a;
    b=b;
}
void test::copy(test obj)
{
    a=obj.a;
    b=obj.b;
}
void test::print()
{
    cout<<test::a<<" <========> "<<b<<endl;
}
int main()
{
    test t1(4,15);
    t1.print();
    test t2=t1;
    t2.print();
}

以上代码应打印 4 <=========> 15 4 <=========> 15

但它正在打印 1733802096 <========> 22093 1733802096 <========> 22093

我没有遇到问题。 如果我在构造函数中更改参数名称,则会给出正确的输出。 发生这种行为的原因可能是什么?

1 个答案:

答案 0 :(得分:2)

您要在此处重新分配参数:

test::test(int a,int b){
    a=a;  // You just set parameter a to its own value!
    b=b;
}

不同于:

test::test(int a,int b){
    this->a=a;
    this->b=b;
}

,应替换为:

test::test(int a,int b) : a(a), b(b) {}

一起。

相关问题