gpt4 book ai didi

c++ - 结构构造函数+函数参数

转载 作者:搜寻专家 更新时间:2023-10-31 00:22:56 25 4
gpt4 key购买 nike

我是 C++ 初学者。我有以下代码,结果不是我所期望的。问题是为什么,resp。怎么了。可以肯定的是,大多数人第一眼就看到了。

struct Complex {
float imag;
float real;
Complex( float i, float r) {
imag = i;
real = r;
}
Complex( float r) {
Complex(0, r);
}
std::string str() {
std::ostringstream s;
s << "imag: " << imag << " | real: " << real << std::endl;
return s.str();
}
};
class Complexes {
std::vector<Complex> * _complexes;
public:
Complexes(){
_complexes = new std::vector<Complex>;
}
void Add( Complex elem ) {
_complexes->push_back( elem );
}
std::string str( int index ) {
std::ostringstream oss;
Complex c = _complexes->at(index);
oss << c.str();
return oss.str();
}
};
int main(){
Complexes * cs = new Complexes();
//cs->Add(123.4f);
cs->Add(Complex(123.4f));
std::cout << cs->str(0); return 0; }

现在我对 C++ 的基础知识感兴趣,而不是复数理论 ;-)如果“添加”函数也接受一个实数(没有额外的重载)而不是仅接受一个复杂对象,那就太好了,这可能吗?

非常感谢
糟糕

最佳答案

你不能像这样在另一个构造函数的主体中调用一个构造函数:

Complex( float r) {
Complex(0, r);
}

在 C++ 中,它创建一个 Complex 类的临时对象,该对象立即被销毁。

您可以在构造函数中使用默认参数或一些将由构造函数调用的私有(private)方法

关于c++ - 结构构造函数+函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705183/

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