【问题标题】:Can I make a constructor in C++ of different data types? [closed]我可以在 C++ 中创建不同数据类型的构造函数吗? [关闭]
【发布时间】:2021-08-30 07:56:19
【问题描述】:

我有一个具有不同数据类型的多个数据成员的类。我想知道是否可以使用构造函数创建和初始化对象。

class test
{
     public:
            int a;
            string b;
            float c;

      test (int x, string y, float z);

};


int main()
{

    test t1(10,"Hello",2.5f); //this line doesn't work

}

【问题讨论】:

  • “我想知道是否可以使用构造函数创建和初始化对象。” - 这基本上是构造函数存在的唯一原因;)请在您的问题中添加更多细节澄清 究竟是什么 不起作用。您只声明了构造函数,但从未在显示的代码中定义它。你也没有包括<string>
  • 是的,你可以这样做。请显示更完整的示例以及您遇到的确切错误。
  • 哦该死,我的糟糕,我完全忘记定义构造函数,我一直忘记定义它们并认为值会自动分配,我应该在构造函数中分配值,谢谢@churill我的愚蠢错误

标签: c++ class constructor initialization


【解决方案1】:

你需要实现构造函数test (int x, std::string y, float z);不要忘记#include <string>在你的源文件的顶部。

虽然你可以使用符号

test t1{10, "Hello", 2.5f};

这将导致参数按写入顺序分配给类成员;尽管您必须完全删除构造函数。

【讨论】:

    【解决方案2】:

    它不起作用这一事实并不是我们在 StackOverflow 上所做的。您应该提供一条错误消息。

    话虽如此,我想您从链接器收到错误,因为您的构造函数不包含定义,而只包含声明。

    这是一个工作示例:https://godbolt.org/z/r89cf86s3

    #include <string>
    
    class test
    {
    public:
        int a;
        std::string b;
        float c;
    
        test (int x, std::string y, float z) : a{x}, b{y}, c{z}
        {}
    };
    
    
    int main()
    {
        test t1(10, "Hello", 2.5f);
    }
    

    注意std::string 按值传递给构造函数可能会导致创建临时对象,因此为了保持此代码的工作并改进它,您可以使用 const 引用,即 @ 987654325@作为构造函数的参数。

    【讨论】:

    • 刚刚知道了,谢谢,我也不知道我们可以分配 a{x}、b{y} 等值,再次感谢
    • @Free-Man I hate to be that guy, but... 这将导致不必要的临时性。
    • @AyxanHaqverdili “通常暗指“我喜欢成为那个人”,“:P
    • @AyxanHaqverdili 因为std::string 没有作为常量引用传递你的意思是?还有其他的吗?
    • @Victor 是的,那个。你也可以采取按价值和移动。这也可以避免额外的副本。
    【解决方案3】:

    在您的示例中,您声明了构造函数,但从未定义它。

    class test
    {
    public:
        int a;
        std::string b;
        float c;
    
        test(int x, std::string y, float z) : a(x), b(y), c(z) {}
    };
    
    
    int main()
    {
        test t1(10, "Hello", 2.5f);
    }
    

    【讨论】:

      【解决方案4】:

      我忘了定义构造函数:(

      应该是这样的:-

      class test
      {
           public:
                  int a;
                  string b;
                  float c;
      
            test (int x, string y, float z)
          {
              a=x;
              b=y;
              c=z;
      
           }
      
      };
      

      int main() {

      test t1(10,"Hello",2.5f); //this line doesn't work
      

      }

      【讨论】:

      • 我们都回答过,是的:)
      • @Bathsheba 你can。对象在它们自己的构造函数/析构函数中不是 const。
      • @AyxanHaqverdili,对不起,高级时刻。我会提出真正的原因。
      • 在构造函数中首选使用基成员初始化,以便可以设置 const 成员。
      • 当你写“应该是这样的”时,你把标准放高了一点,不使用成员初始化器列表对我来说是不合格的。在这里阅读:stackoverflow.com/questions/926752/…
      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 2012-04-10
      相关资源
      最近更新 更多