没有参数的默认构造函数是否始终初始化变量?

时间:2017-03-23 15:37:43

标签: c++ visual-c++

我有一个包含默认构造函数的类,该构造函数应该初始化几个私有成员变量。我想知道我的变量是否曾被初始化,因为当我调用variables_in_class方法时,没有打印任何内容。有人可以向我解释一下吗?我的代码如下:

class Practice_Class
{
public:
Practice_Class()
{
  a = 6;
  b = 89;
  c = 45;
}
  void variables_in_class()
  {
    cout << a << " "<< b << " "<< c << " "<< endl;
  }

private:
    int a, b, c;

};


int main()
{
 Practice_Class the_value;
 cout << the_value.variables_in_class();

}

2 个答案:

答案 0 :(得分:4)

这应该有效:

int main()
{
    Practice_Class the_value;

    // you are outputing in variables_in_class(), not its return values
    the_value.variables_in_class();
}

对于你的问题:

没有参数的默认构造函数是否会初始化变量?

  

没有。如果你在默认构造函数中什么都不做,它会自动调用类成员&#39;默认构造函数。除此之外,它什么也没做。

答案 1 :(得分:2)

  

我有一个包含默认构造函数的类   初始化几个私有成员变量。

你没有初始化你的。你分配他们。以下是使用初始化列表的正确方法:

Practice_Class() :
  a(6),
  b(89),
  c(45)
{
}
  

我想知道我的变量是否曾被初始化,因为当我调用variables_in_class方法时,没有打印任何内容。

代码甚至不应该编译。见下文:

cout << the_value.variables_in_class();

variables_in_class()是一个void函数(在这个函数中命名非常差)。它没有返回任何东西。它在内部使用流 这一事实在呼叫站点无关紧要。您无法将不存在的函数结果传递给std::cout。只需调用函数:

the_value.variables_in_class();

尽管如此,惯用的C ++方法是为您的类提供相应的输出流重载,以便您可以将类的实例传递给std::cout或其他输出流。

示例:

#include <iostream>

class Practice_Class
{
public:
    Practice_Class() :
        a(6),
        b(89),
        c(45)
    {
    }

private:
    // so that the function below can access the variables:
    friend std::ostream& operator<<(std::ostream& os, Practice_Class const& obj);

    int a;
    int b;
    int c;
};

std::ostream& operator<<(std::ostream& os, Practice_Class const& obj)
{
    os << obj.a << " " << obj.b << " " << obj.c;
    return os;
}

int main()
{
    Practice_Class the_value;
    std::cout << the_value << '\n';
}
相关问题