【问题标题】:C26495 Variable 'Employee::age' is uninitialized. Always initialize a member variable (type.6)C26495 变量 'Employee::age' 未初始化。始终初始化成员变量(type.6)
【发布时间】:2021-06-21 11:11:56
【问题描述】:

这是我的代码:-

#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 的内容

请帮忙。

【问题讨论】:

  • 你希望像age = age; 这样的作业能做什么?
  • age = age; -- 我很惊讶你没有对此感到困惑,因为你有一个同名的参数和一个成员变量。
  • 你应该改变你的编码风格,让参数和成员有不同的名字。

标签: c++ visual-studio class constructor scope


【解决方案1】:

这个构造函数

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

在 main 中你可以写

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;

是多余的。

【讨论】:

    【解决方案2】:

    您的构造函数只是将给构造函数的参数分配给自己:

    Employee(string company, string name, int age) {
                     //              ^
                     //              |
        name = name; // -------------+ both left and right name refer to the argument
        company = company;
        age = age;
    }
    

    您可以通过为构造函数参数使用不同的名称(或通过使用 this-&gt;member = ... 显式使用)或使用 member initializer-list 来解决它:

    Employee(string company, string name, int age) : // colon starts the member init-list
        name(name),        // The first name refers to the member varible (this->name)
        company(company),  // and the second refers to the constructor argument
        age(age)           //
    {
        // constructor body can now be empty
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2012-08-23
      • 2014-09-08
      相关资源
      最近更新 更多