Problem with ctor in C++
2011-05-22 10:54
288 查看
Sometimes you've got to admit that you're stupid when you did do
something really stupid. I wrote some code that makes myself crashed several
days ago. I mark it down now and tt can be simplified like the following:
#include <stdio.h> class A { public: A(int x, int y) { a1 = x; a2 = y; a3 = 0; } A(int z) { A(1, 2); a3 = z; } public: int a1; int a2; int a3; }; int main() { A a(3); printf("a1 = %d, a2 = %d, a3 = %d/n", a.a1, a.a2, a.a3); }
Don't ask me why I'm too silly to write one ctor to
initialize three int -_-!!, this code is just simple enough to illustrate the
problem. It seems fine at the first glance but actually it may ruin your whole
life especially when code go far more complicated in inheritance hierarchy. If
you do not figure it out, let's look at line 5,in fact
A(1, 2); doesn't do anything you expected; Unfortunately it's
not a function call to initialize
the this object instead it calls A::A() to initialize
a temporary, local object (not this), then it
immediately destructs that temporary when control flows over the
;(semicolon), this means you left a1 and a2 uninitialized. In C++ one
constructor cannot call another constructor of the same class, and one of the
solutions to the problem above can be:
#include <stdio.h> class A { public: A(int x, int y) { Init(x, y); } A(int z) { Init(1, 2); a3 = z; } private: void Init(int x, int y) { a1 = x; a2 = y; a3 = 0; } public: int a1; int a2; int a3; }; int main() { A a(3); printf("a1 = %d, a2 = %d, a3 = %d/n", a.a1, a.a2, a.a3); }
相关文章推荐
- Solve an LP problem in C++ using Gurobi
- Web Service with Https in C++ 非托管方式
- Problem with ReportViewer (Q1 2014) rendering in IE 10 or 11
- Getting OS version with NDK in C c++获得版本号
- Are there dictionary comprehensions in Python? (Problem with function returning dict)
- Problem with driver "Derby Embedded JDBC Driver 10.0 Default." (Error: Unable to locate JAR/zip in f
- Any problem in computer science can be solved with another layer of indirection
- Any problem in computer science can be solved with another layer of indirection
- [Tutorial] How to build a GUI in ROS with Qt / C++?
- Embedding Python in C++ Applications with boost::python
- Introduction to Programming in C/C++ with Vim
- Using SQLite in C++ with Code::blocks
- How To Fix “Problem with MergeList /var/lib/apt/lists” Error In Ubuntu 11.04
- This problem will occur when running in 64 bit mode with the 32 bit Oracle client components installed
- ios 提交 App Store Error Problem with Icon.png (Icon specified in the Info.plist not found under the t
- Problem in calling C++ dll from C# Code
- Problem with Anonymous delegate in loop
- Detecting Application Memory leaks in Unmanaged C++ with 4 lines of code:
- Creating an AVI in memory with C++
- GCC 6.1 (C++17) doesn't compile std::atomic<std::chrono::system_clock::time_point> with default ctor