调用这个不存在的构造函数时会发生什么? 编译C++代码时,在最后一行中出错。 #include <iostream> class TestClass { public: TestClass(int val) : value(val) { } int getValue() { return value; } private: int value; }; int main() { TestClass b(); std::cout << b.getValue() << std::endl; }
现在我的问题是:b到底包含什么?编译器不会抱怨TestClass b。您有一个令人烦恼的解析:调用这个不存在的构造函数时会发生什么? 编译C++代码时,在最后一行中出错。 #include <iostream> class TestClass { public: TestClass(int val) : value(val) { } int getValue() { return value; } private: int value; }; int main() { TestClass b(); std::cout << b.getValue() << std::endl; },c++,constructor,C++,Constructor,现在我的问题是:b到底包含什么?编译器不会抱怨TestClass b。您有一个令人烦恼的解析: TestClass b(); // This is a declaration of function b which return TestClass. 如果您有默认构造函数,请使用: TestClass b; 或 但由于您只有带int参数do的构造函数 TestClass b(42); 或 它是一个函数声明。外面有很多复制品,你说得对。有趣的是,我可以在main中声明函数,但不能定义函数。
TestClass b(); // This is a declaration of function b which return TestClass.
如果您有默认构造函数,请使用:
TestClass b;
或
但由于您只有带int参数do的构造函数
TestClass b(42);
或
它是一个函数声明。外面有很多复制品,你说得对。有趣的是,我可以在main中声明函数,但不能定义函数。
TestClass b{};
TestClass b(42);
TestClass b{42};