构造函数不返回可用对象 [英] Constructor not returning usable object
问题描述
我的构造函数有问题,它无法按预期工作.
I have a problem with the constructor, which is not working as I'd expect.
如果我尝试像这样初始化我的类,它将起作用并且我得到一个可用的对象:
If I try to initialize my class like that, it will work and I get a usable object:
vector<float> v;
MyClass<2> a(v);
但是,如果我尝试构建如下所示的类(应该是等效的),结果将是非常意外的.编译或运行程序时,没有错误消息/警告.但是,如果您尝试在某个地方使用此变量并调用其方法(例如a.doSomething()),它将崩溃.
However, if I try to build a class like below (which should be equivalent) the results are quite unexpected. There is no error message/warning when compiling or running the program. But if you try to use this variable a somewhere and call its methods (for example a.doSomething()), it will crash.
我在构造函数中放入了一些代码,以通知我是否使用了它.事实证明,在这种情况下,构造函数内部实际上没有执行任何代码.
I put some code inside the constructor to notify me if it is used. It turned out that no code inside the constructor was actually executed in this case.
MyClass<2> a(vector<float>());
所以我想知道为什么会这样吗?第二条声明是否违法?
So I am wondering why this is happening? Is the 2nd declaration illegal?
我将发布该类的一些代码
I will post some code of the class
template <int x>
class MyClass {
public:
vector<float> v;
MyClass<x>(vector<float> v1) {
v = v1;
}
};
推荐答案
MyClass<2> a(vector<float>());
这不是变量声明.它是一个名为 a
的函数的声明,该函数返回一个 MyClass< 2>
对象,并以指向不带任何参数并返回一个a的函数的指针"作为参数. vector&float>
."令人困惑?是的.这就是所谓的最烦人的解析".
This is not a variable declaration. It is the declaration of a function named a
that returns a MyClass<2>
object and takes as an argument a "pointer to a function that takes no arguments and returns a vector<float>
." Confusing? Yes. This is what is referred to as the "most vexing parse."
您需要额外的括号:
MyClass<2> a((vector<float>()));
^ ^
或者,您可以使用副本初始化:
Or, you can use copy initialization:
MyClass<2> a = MyClass<2>(vector<float>());
或者,由于您的构造函数不是 explicit
,因此您可以使用:
Or, since your constructor isn't explicit
, you could use:
MyClass<2> a = vector<float>();
(尽管,除非您要使 vector< float>
对象隐式转换为 MyClass< N>
对象,否则您可能希望使此构造函数成为明确的
.)
(Though, unless you mean for vector<float>
objects to be implicitly convertible to MyClass<N>
objects, you probably want to make this constructor explicit
.)
一个好的编译器应该警告您这种事情.Visual C ++警告:
A good compiler should warn you about this sort of thing. Visual C++ warns:
警告C4930:'
MyClass< x>a(std :: vector< _Ty>(__cdecl *)(void))
':未调用原型函数(是否打算使用变量定义?)
warning C4930: '
MyClass<x> a(std::vector<_Ty> (__cdecl *)(void))
': prototyped function not called (was a variable definition intended?)
C警告:
警告:括号已明确地作为函数声明符
warning: parentheses were disambiguated as a function declarator
MyClass<2> a(vector<float>());
^~~~~~~~~~~~~~~~~
这篇关于构造函数不返回可用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!