首页 > 解决方案 > 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 的内容

请帮忙。

标签: c++visual-studioclassconstructorscope

解决方案


这个构造函数

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;

是多余的。


推荐阅读