首页 > 解决方案 > 实现复制的简单 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

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

标签: c++

解决方案


您在此处重新分配参数:

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) {}

全部一起。


推荐阅读