构造函数不返回可用对象
我的构造函数有问题,它没有按我的预期工作。
如果我尝试像这样初始化我的类,它将起作用并且我得到一个可用的对象:
vector<float> v;
MyClass<2> a(v);
但是,如果我尝试构建如下所示的类(应该是等效的),结果是相当意外的。编译或运行程序时没有错误消息/警告。但是,如果您尝试在某处使用此变量 a 并调用其方法(例如 a.doSomething()),它将崩溃。
我在构造函数中放置了一些代码来通知我是否使用了它。事实证明,在这种情况下,构造函数内的代码实际上没有被执行。
MyClass<2> a(vector<float>());
所以我想知道为什么会发生这种情况?第二次申报违法吗?
编辑:我将发布该类的一些代码
template <int x>
class MyClass {
public:
vector<float> v;
MyClass<x>(vector<float> v1) {
v = v1;
}
};
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);
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?
EDIT: I will post some code of the class
template <int x>
class MyClass {
public:
vector<float> v;
MyClass<x>(vector<float> v1) {
v = v1;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是变量声明。它是一个名为
a
的函数的声明,该函数返回一个MyClass<2>
对象,并将“指向不带参数并返回 < 的函数的指针”作为参数。代码>矢量<浮点>。”令人困惑?是的。这就是所谓的“最令人烦恼的解析”。您需要额外的括号:
或者,您可以使用复制初始化:
或者,由于您的构造函数不是
显式
,您可以使用:(不过,除非您的意思是
vector
) code> 对象隐式转换为MyClass
对象,您可能希望使该构造函数显式
。)一个好的编译器应该警告您此类事情。 Visual C++ 警告:
Clang 警告:
This is not a variable declaration. It is the declaration of a function named
a
that returns aMyClass<2>
object and takes as an argument a "pointer to a function that takes no arguments and returns avector<float>
." Confusing? Yes. This is what is referred to as the "most vexing parse."You need extra parentheses:
Or, you can use copy initialization:
Or, since your constructor isn't
explicit
, you could use:(Though, unless you mean for
vector<float>
objects to be implicitly convertible toMyClass<N>
objects, you probably want to make this constructorexplicit
.)A good compiler should warn you about this sort of thing. Visual C++ warns:
Clang warns: