【发布时间】: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