gpt4 book ai didi

c++ - 类构造函数、重载构造函数和对象初始化

转载 作者:太空宇宙 更新时间:2023-11-04 13:14:43 26 4
gpt4 key购买 nike

来自C++ tutorial , 类 (I) 章,重载构造函数:

But this example also introduces a special kind constructor: the default constructor. The default constructor is the constructor that takes no parameters, and it is special because it is called when an object is declared but is not initialized with any arguments. In the example above, the default constructor is called for rectb. Note how rectb is not even constructed with an empty set of parentheses - in fact, empty parentheses cannot be used to call the default constructor:

Rectangle rectb;   // ok, default constructor called
Rectangle rectc(); // oops, default constructor NOT called

This is because the empty set of parentheses would make of rectc a function declaration instead of an object declaration: It would be a function that takes no arguments and returns a value of type Rectangle.

所以,据我了解:

class someclass {
public:
someclass() {
std::cout << "Default constructor" << std::endl;
}
someclass(int arg) {
std::cout << "Constructor that uses passed argument (" << arg << " in this case)" << std::endl;
}
};


int main() {
someclass object1;
//outputs "Default constructor"

someclass object2(1294);
//outputs "Constructor that uses passed argument (1294 in this case)"
}

但是我如何定义一个被调用为 someclass object(); 的构造函数?我的想法是 someclass(void) {}(对此不确定)或使用参数的默认值 (someclass(int arg = 1294) {}),但是这个案例是如何正确处理的?

最佳答案

你可以使用冗长的构造方式:

 someclass object1 = someclass();

someclass object(); 不会调用,因为编译器认为它是一个函数声明,不带参数并返回一个 someclass 实例。

关于c++ - 类构造函数、重载构造函数和对象初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37901534/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com