简体   繁体   English

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

[英]Wrong output in simple c++ program implementing copy

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

The above code should print 4 <========> 15 4 <========> 15 上面的代码应打印4 <========> 15 4 <=========> 15

but it is printing 1733802096 <========> 22093 1733802096 <========> 22093 但它正在打印1733802096 <========> 22093 1733802096 <=========> 22093

I am not getting the problem. 我没有问题。 if I change the parameter name in the constructor it is giving correct output. 如果我在构造函数中更改参数名称,则会给出正确的输出。 What could be the reason for such behavior?? 发生这种行为的原因可能是什么?

You are reassigning your parameters here: 您要在此处重新分配参数:

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

is not the same as: 与以下内容不同:

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

and should be replaced with: 并应替换为:

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

all together. 全部一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM