【问题标题】:Cpp/C++ Assign Default value to default constructorCpp/C++ 为默认构造函数分配默认值
【发布时间】:2022-01-04 20:02:36
【问题描述】:

这似乎是一个非常简单的问题,但我找不到可行的解决方案(也许它也是代码的其余部分)。 所以基本上,当自定义构造函数将该变量作为参数时,如何为使用默认构造函数创建的对象赋值? (希望这是可以理解的)

也许更清楚: 下面的代码只有在我在 main 函数中写 foo ex2(2) 而不是 foo ex2() 时才有效。那么如果对象是使用默认构造函数创建的,我该如何为x 分配默认值

class foo {

public:
    int y;
    int x;
    static int counter;

    foo()
    {
        y = counter;
        counter++;
        x = 1;
    };

    foo(int xi) 
    {
        y = counter;
        counter++;
        x = xi;
    };

};

int foo::counter = 0;

int main()
{

    foo ex1(1);
    foo ex2();

    std::cout << ex1.y << "\t" << ex1.x << "\n";
    std::cout << ex2.y << "\t" << ex2.x << "\n";
    std::cin.get();
};

【问题讨论】:

  • 您已经使用 x = 1; 分配了一个值 - 我不确定您还想做什么
  • 您应该打开所有编译器警告:warning: empty parentheses were disambiguated as a function declaration [-Wvexing-parse] -> What is the purpose of the Most Vexing Parse?
  • @UnholySheep 我的问题是 ex2 的对象声明错误,所以它不起作用。泰寿:)

标签: c++ class constructor declaration default-constructor


【解决方案1】:

这条记录

foo ex2();

不是类 foo 的对象声明。

这是一个函数声明,返回类型为foo,没有参数。

你需要写

foo ex2;

foo ( ex2 );

foo ex2 {};

foo ex2 = {};

【讨论】:

    【解决方案2】:

    如上所述。然后分配一个默认值:

    class foo {
    public:
        int y;
        int x;
        static int counter;
        foo(int xi = 1) : x(xi)
        {
            y = counter;
            counter++;
        };
    };
    int foo::counter = 0;
    
    int main()
    {
        foo ex1(3);
        foo ex2;
    
        std::cout << ex1.y << "\t" << ex1.x << "\n";
        std::cout << ex2.y << "\t" << ex2.x << "\n";
    };
    

    【讨论】:

    • 实际上,与为xi 提供默认值相比,您对原始代码进行了另一个更重要的更改。
    • 嗨@churill,您是指foo ex2; 部分吗?
    • Excatly :) foo ex2();(与原版一样)在您的版本中也会失败。
    猜你喜欢
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2022-10-23
    • 2013-03-16
    • 1970-01-01
    相关资源
    最近更新 更多