c++ - C26495 变量 'Employee::age' 未初始化。始终初始化成员变量(type.6)
问题描述
这是我的代码:-
#include<iostream>
using std::string;
//bydefault private cant access attributes outside class
class Employee{
public:
string name;
string company;
int age=0;
void Introduce() {
std::cout << "my age is- " << age << std::endl;
}
Employee(string company, string name, int age) {
name = name;
company = company;
age = age;
}
};
int main() {
Employee emp1 = Employee("bww","susmit",24);
emp1.Introduce();
//Employee emp2;
//same example
}
输出是我的年龄是0
我希望它是我输入 emp1 args 的内容
请帮忙。
解决方案
这个构造函数
Employee(string company, string name, int age) {
name = name;
company = company;
age = age;
}
是不正确的。在构造函数的主体中,您正在为自己分配参数。这是因为参数隐藏了构造函数体内的同名数据成员。
至少你应该写
Employee(string company, string name, int age) {
this->name = name;
this->company = company;
this->age = age;
}
但使用 mem-initializer 列表会更好
Employee(const std::string &company, const std::string &name, int age)
: name( name ), company( company ), age( age )
{
}
主要是你可以写
Employee emp1("bww","susmit",24);
代替
Employee emp1 = Employee("bww","susmit",24);
至于函数Introduce
,最好通过以下方式声明和定义它
std::ostream & Introduce( std::ostream &os = std::cout ) const
{
os << "my age is- " << age << std::endl;
return os;
}
声明这些数据成员也没有什么意义
string name;
string company;
int age=0;
作为具有公共访问权限。您可以将它们声明为具有私有访问权限。
此外,由于您的类没有默认构造函数,因此该成员在类定义中初始化
int age=0;
是多余的。
推荐阅读
- xml - 使用 XSLT 将所有节点包装在 2 条处理指令之间
- c# - ArgumentException:无法转换类型的对象。但我有一个隐式运算符 C#
- http - 内容类型多参数
- python - 使用python创建地图
- swift - 在 SwiftUI 视图中一起分配属性值?
- python - Slack 不展开图像链接以显示预览图像
- object-detection-api - 使用对象检测 API 微调具有不同类数的模型
- html - W3 CSS 和正文滚动锁定
- sqlite - 如何从 UIPath 对 SQLite DB 进行 CRUD 更新
- flutter - 新状态不调用 Flutter BlocBuilder