c++ - 实现复制的简单 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
我没有得到问题。如果我在构造函数中更改参数名称,它会给出正确的输出。这种行为的原因可能是什么?
解决方案
您在此处重新分配参数:
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) {}
全部一起。
推荐阅读
- javascript - 导航栏在桌面屏幕上悬停并在移动设备上单击时出现问题
- spring - 如何修复此 FirebaseApp 名称 [DEFAULT] 已存在!spring-boot 和 firebase
- java - Spring MVC 中的模型
- javascript - 永久夜间模式切换
- typo3 - 如何设置 TYPO3 RTE 向导的尺寸?
- angular - 我可以从 cmd 窗口“服务”驻留在 C:/SuperApp 中的我的应用程序吗 C:/OtherFolder>
- java - SpringBoot + RabbitMQ 抛出错误:java.net.ConnectException:连接被拒绝
- vb.net - 使用复选框防止焦点更改到 Datagridview 中的下一行
- javascript - 显示错误“未知的自定义元素
" - jquery - 如何使用左侧文本和右侧图像 Bootstrap 4 制作 div