我面临着一个非常困惑的问题。 我正在尝试使用一个变量作为参数来构造一个对象。
请看一下这段代码:
#include <iostream>
class A {
public:
A() : val(0) {};
A(int v) : val(v) {};
private:
int val;
};
main() {
int number;
A a; /* GOOD, object of type A, created without arguments */
A b(2); /* GOOD, object of type A, created with one argument */
A c(); /* BAD, C++ thinks this is declaration of
a function returning class A as a type */
A(d); /* GOOD, object of type A again; no arguments */
A(number); /* BAD, tries to re-declare "number" as object of type A */
}
我认为我了解为什么可以创建 "a"、"b" 和 "d" 对象,而其他对象则不能。
但是我确实需要最后声明的语法,即:
A(number);
创建临时对象,并将其作为参数传递给另一个对象。
有什么办法可以解决这个问题吗?
Kind regards
(A(number));
或者static_cast<A>(number);
- jrokA( (int)number );
- user2664344