为什么我们在没有它们的情况下也可以使用构造函数来初始化值?

时间:2017-12-10 04:37:19

标签: c++

请同时考虑以下代码。一个使用构造函数初始化值,而一个不使用。

代码#1

#include<iostream>
using namespace std;
class Rectangle
{
public:
int width;
int height;
};

int main()
{
Rectangle rect1{3,4};
cout<<"Width="<<rect1.width<<endl;
cout<<"Height="<<rect1.height<<endl;
return 0;
} 

我得到输出为

宽度= 3

高度= 4

代码#2

#include<iostream>
using namespace std;
class Rectangle
{
public:
int width;
int height;
Rectangle(int a,int b)
{
width=a;
height=b;
}
};
int main()
{
Rectangle rect1(3,4);
cout<<"Width="<<rect1.width<<endl;
cout<<"Height="<<rect1.height<<endl;
return 0;
}

我得到相同的输出。 我的问题可能很简单但是,当我在两种情况下获得相同的输出时,为什么还要使用构造函数。 提前致谢

4 个答案:

答案 0 :(得分:1)

答案很简单,构造函数初始化,其他方法分配。

差异可能看起来不是很大,但请考虑这段代码。

rs1065852 rs201377835 rs28371706 rs5030655 rs5030865 rs3892097 rs35742686 rs5030656 rs5030867 rs28371725 rs59421388
         A           C          G         A         C         T          T       CTT         T          C          C
       del         del        del       del       del       del        del       del       del        del        del 

此代码会出现编译错误,指出#include<iostream> using namespace std; class Sample { private: const int num; public: void setval(int i) { num = i; } int getVal() { return num; } }; int main() { Sample s; s.setval(12); cout<<s.getVal(); } 已声明为const,我们正试图通过使值等于num来将值分配给num

因为iconst必须在references initialized之后declaration constructors完成此作业。

此外,让您的班级成员保密,这是一个很好的做法,而且更加面向对象。

所以上面的代码应该是。

initializing

答案 1 :(得分:0)

对于这样的简单数据类型,它可能无关紧要,但是有许多非普通旧数据类型可以从中受益,甚至需要初始化才能完全有用。

答案 2 :(得分:0)

构造函数有几个好处:

  • 构造函数允许公共API(封装)。在更复杂的类中,可能需要初始化调用者不应该触摸的内部数据。

    class Foo
    {
    public:
        Foo(int x) {
            internal_data1 = some_computation1(x);
            internal_data2 = some_computation2(x);
        }
    
        Some_Type3 some_method(int x)
        {
            return some_computation3(x, this->internal_data1, this->internal_data2);
        }
    private:
        Some_Type1 internal_data1;
        Some_Type2 internal_data2;
    };
    
  • 有几个涉及构造函数的C ++概念,例如DefaultConstructible和CopyConstructible。构造函数提供了一个通用接口,因此通用代码可以统一的方式实例化不同类型的对象。

    template<class T>
    class Some_Generic
    {
    public:
        Some_Generic(const T& t)
          : internal_t(t) // Copy constructor used
        {
            // do work...
        }
    private:
        T internal_t;
    };
    

答案 3 :(得分:0)

构造函数已经内置在程序中,如果你不添加参数化构造函数,程序本身将自己创建一个默认构造函数,并且不会显示,所以最好添加构造函数并初始化类的变量

相关问题